I am trying to make an ajax call and return a response. The problem is I can't seem to figure out how to get at the response. Here is my javascript code:
$.ajax({
type: "POST",
url: "inc.test.php",
data: {list:postData},
dataType: "json",
success: function(response){
if(response.success == 1){
alert (response.testdata);
}},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
console.log(textStatus);
}
});
Here is my inc.test.php code sending the json data back:
if($result)
{
$arr=array(
"success" => 1,
"testdata" => 'Testing');
echo json_encode($arr);
}
In my Console/Response I see this:
{"success":1,"testdata":"Testing"}
I've read tons of articles and can't seem to figure out whats going on. Please help!
Did you try using PHP's trim()
function before sending the data? i think you have an extra space when you json_encode
or use trim()
.
if($result)
{
$arr=array(
"success" => 1,
^
"testdata" => 'Testing');
^
echo json_encode($arr);
}
success: function(response) { var resp = JSON.parse(response); // rest of code ... }
May be because you have parse your code? You didn't specify what the issue is.
if this is in wordpress , you may forgot to
wp_die();
in the end of php function called by ajax request
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.