Codes
####### The name of this file is 'test_ajaxfn.php' #######
<?php
if($_POST['var']) {
$result = $_POST['var'];
echo $result.' is successfully passed to the same page using Ajax Post. :)';
} else {
echo 'There is no POST variable passed to the same page. :( ';
}
echo '<br> Above indicates the ajax post function \'.\' ';
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#clickdiv').click(function() {
var sth = "value to send to PHP";
$.post(
'test_ajaxfn.php',
{"var":"1234567"},
function(){
alert('success');
$('#clickdiv').text('the POST variable should be posted.');
}
);
});
});
</script>
</head>
<body>
<div id="clickdiv" style="width: 50px; height: 50px; background:#CC3300; cursor:pointer;">
</div>
</body>
</html>
Description
I want to pass POST variable to the same page and load it using AJAX. However, I failed to do so. I can’t pass the “var” to $_POST[‘var’] using POST method. Hence I can’t display the following:
echo $result.’ is successfully passed to the same page using Ajax Post. :)’;
What have I done wrong?
Reference
I was actually trying to tackle this problem:
Calculate Google distance of Input address and all the address from MySQL Server using jQuery ajax.get
Now I simplify my problem but still it doesn’t work. Please help 🙁
If you post it to the same page the server creates a new process to handle the request. The reason you are not seeing any output is because the server is seeing a post to a file, spinning up an instance and executing the php script but that is different from your php thread. Change your script to this to see your success text.