简体   繁体   中英

Why php json response does not send back the data array to ajax jquery request?

I have made an ajax request to the php server where I send a data from a form request and I would to get back the same data from the server just for testing requests and responses of the same data throwing between the client and the server.

$.ajax({
    method: "POST",
    url: "addRaces",
    dataType: "json",
    data : sending_data,
    success : ...
})

sending_data is an array like {field_form_name : value}

The server responds to the request with the following code :

$data = [];
foreach ($request->Input() as $key => $value) {
    $data[$key] = $value;
}

return json_encode($data);

The same data should come back to the client, but nothing happen with an alert(response) or a jquery showing debug data like $('#debug').html(response);

The strange thing coming up when I try to push the server answer like

return json_encode([
  'debug' => $data['name']
]);

and showing results to client like

$('#debug').html(response.debug);

it is working for a single key-value response showing the properly value field I have send from the client. Other wise whether I send the full data as an array nothing is shown in the debug area of the client.

return json_encode($data); wont work. as it is returning the json string to the calling method which is not your jQuery at front end. Don't confuse front end (html javascript, jQuery, etc...) with back end (PHP) the two of them are running in different machines. One at client end and another at your server.

you should use echo json_encode($data); this will output the json string and your web server will send it to the front end.

Make sure you are echoing the data not returning as @bansi said, if you are echoing it already then debug using var_dump(json_encode($data)) . If json_encode() found errors it will return False instead of the expected json array.

You should debug using the developer tools instead of using code $('#debug').html(response.debug); . The Network tab of developer tools is very useful to debug HTTP requests, it will show response header and body of your requests.

In your case, just change return to echo like @bansi's answer . The return command does not print the data so you did not get anything in the response.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM