Suppose I run this ajax -
$.ajax({
url: "index.php",
type: 'POST',
data :{test : 123}, //updated due to the approved answer
dataType: 'json'
});
and I want to get its json content in - index.php
and alert
its test
value (mean get - 123
) ,
I tried this -
index.php-
<?php
$json = $_POST["test"];
echo '<script>';
echo 'alert('+$json+');';
echo '</script>';
?>
but nothing was alerted .
How to handle it correctly ?
Update:
Following @JayBlanchard comment,
does $json = $_POST["test"]
is really get the test
value ?
The alert
isn't important for me , I just want to ensure whether it's parsed correctly in the PHP side , mean get the 123
back to the client side .
You need to handle the results from your php in your JavaScript callback. So you could do this:
$.ajax({
url: "index.php",
type: 'POST',
data :{text : 123},
dataType: 'json',
complete: function(data){
console.log(data.responseText) //(not sure why responseText is necessary)
}
});
Your php would be something like:
<?php
$json = $_POST["text"];
echo $json;
?>
You would do this simply in the success
callback:
$.ajax({
url: 'index.php',
type: 'post',
data: {text : 123},
dataType: 'json',
success: function(data) {
alert(data.test);
}
});
And your index.php
:
<?php
echo json_encode(array('test' => $_POST['test']));
?>
You have to define a javascript function to handle response:
var handle_response = function(data_from_server, StatusText, jqxhr) {
// check http://api.jquery.com/jquery.ajax/ for StatusText and jqxhr meaning.
alert(data_from_server);
}
Then you call your ajax
$.ajax({
url: "index.php",
type: 'POST',
data :{text : 123},
dataType: 'json',
success: handle_response
});
your php will be something like
<?php
$json = json_decode($_POST["text"]); // not sure about dataType: 'json'
echo "this is coming from php on server ";
?>
if you want to execute some script created from the server check on jquery manual how to do it safely.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.