I tried to get a simple ajax-test working but without success. I am trying to pass a variable($add1) from PHP to JS, then let the JS calculate the sum and return it back to a PHP variable via $_POST and ECHO it out in the html.
index.php:
<?php
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum($add1)</script>";
$sum = $_POST['variable'];
echo $sum;
?>
script.js:
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
});
}
For some reason this code doesn't work. Any help is appreciated.
I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST.
$sum from $_POST is actually echoed, but not shown in HTML page, but handled as a response back to Ajax.
You have to add a success function in Ajax closure
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function (data){
document.write(data);
}
});
You will see the answer show in page.
php:
if (isset($_POST['variable'])) {
$sum = some_futher_function($_POST['variable']);
echo $sum;
} else {
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum({$add1})</script>";
}
function some_futher_function($param){
//do some thing
return $return;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With