javascript - AJAX call to the same page, without a page refresh
Get the solution ↓↓↓I've been having this problem for around a week now where I just cannot seem to get an AJAX call to communicate with PHP. This is my sample code I've made for this issue
<!DOCTYPE html>
<html>
<head>
<style>
#showInfo
{
height: 100px; width: 400px;
text-align: center;
border: 2px solid darkslategray;
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
margin: auto;
cursor: pointer;
}
#showInfo p
{
font-size: 25px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#showInfo").click(function() {
$.ajax({
type: "POST",
data: { imageDir: "hello" },
success: function(data) {
alert("success");
console.log(data);
},
error: function(data) { alert("error"); }
});
return false;
});
});
</script>
</head>
<body>
<div id="showInfo">
<p> Show "defaultPfp.jpg" directory </p>
</div>
<?php
if (isset($_POST['imageDir']))
echo 'worked';
else
{
echo 'didnt work';
}
?>
</body>
</html>
For clarification, I want this code to be able to send an AJAX call once the #showInfo div is clicked. From here this is where the problem arises. I think that the PHP within the page isn't refreshing to gather the AJAX call's data. IF this is the problem, I have no clue what to do.
Other than this, I've tried adding event.preventDefault() before and after the AJAX call, and I've tried to add some ob_flush() calls all with no luck. Any help is greatly appreciated.
EDIT: A problem that is occuring is that the variable data in the AJAX call is not functioning correctly. console.log(data) returns the entire HTML page, and I'm not sure why.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.