I have a problem with a form, the post and the response. In my form I call a function (javascript) with the ajax post:
var vars = "test="+test;
$.ajax({
type: "POST",
url: "index.php",
data: vars
}).done(function(data) {
alert(data);
}).fail(function(data) {
alert(data);
});
In index.php I receive all the data:
<?php
$test = $_POST['test'];
//do something
?>
After I have to give back a value to the previous php. How can I do?? Thanks
var vars = "test="+test;
$.ajax({
type: "POST",
url: "index.php",
data: vars
success: function(html){
alert(html)
}
});
in index.php, enter follow code and check
<?php
$test = $_POST['test'];
//do something
echo $test
?>
The same way you send data back for any other HTTP request.
header("Content-Type: text/plain"); # Avoid introducing XSS vulnerabilities
echo $test;
If it's a simple value you need to return, you can just echo
it, and it will come back as the response.
If you need to return a more complex structure, you store it in a PHP array, say $response
, and use echo json_encode($response);
to output it back to javascript.
This may help
Javascript
var vars = { test : "test" };
$.ajax({
type: "POST",
url: "index.php",
dataType : 'json',
data: vars,
success : function(data) {
console.log(data);
},
error : function(resp) {
console.log(resp.responseText);
}
});
PHP
<?php
$test = $_POST['test'];
echo json_encode($test);
?>
Try it and check console log
If you have to return data in JSON format then use
echo json_encode($test);
Else you can simply echo the variable which you need in the ajax response. i.e.
echo $test;