Ajax test not working
I tried to get a simple ajax test but with no success. I am trying to pass a variable ($ add1) from PHP to JS, then let JS calculate the sum and return it back to the PHP variable via $ _POST and ECHO in 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.
source to share
I want php file to pass $ add1 to Javascript and then I want javascript to return var back to php and php to echo $ sum from $ POST.
$sum
from $_POST
is actually echoed, but not displayed in the HTML page, but processed as a response back to Ajax.
You have to add a function success
to the Ajax closure
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function (data){
document.write(data);
}
});
You will see the answer on the 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;
}
source to share
Include this on your page before script
.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
Php code
<?php
if ($_POST['variable']) { // If ajax request only
$sum = $_POST['variable'] + $add1;
echo $sum;
} else { // Loading in the browser
$add1 = 3;
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="script.js"></script>';
echo "<script>sum(".$add1.")</script>";
}
?>
Javascript
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function(result) {
alert(result)
},
error: function(e) {
console.log(e);
}
});
}
source to share