I am posting some data using ajax. I want to manipulate that data and return to to the calling jQuery script.
Here is my jQuery:
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function() {
//do something;
}
});
Here is my somescript.php on the server:
<?php
//manipulate data
$output = some_function(); //function outputs a comma-separated string
return $output;
?>
Am I doing this correctly on the server side, and how do I access the return string when开发者_开发问答 the ajax call completes?
I figured it out. Need to use echo in PHP instead of return.
<?php
$output = some_function();
echo $output;
?>
And the jQ:
success: function(data) {
doSomething(data);
}
It's an argument passed to your success function:
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
The full signature is success(data, textStatus, XMLHttpRequest)
, but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
Yes, the way you are doing it is perfectly legitimate. To access that data on the client side, edit your success function to accept a parameter: data.
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
doSomething(data);
}
});
精彩评论