简体   繁体   中英

Error reciving json at server side using ajax

I am trying to send json with ajax to php file for that I have tried below code

  1. Using jquery

     var dummyData = {'bob': 'foo', 'paul': 'dog'}; var ajaxRequest = $.ajax({ url: "json_handler.php", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(dummyData ), dataType: "json" }); ajaxRequest.done(function (response, textStatus, jqXHR) { console.log(response + textStatus + jqXHR); alert('sd'); }); ajaxRequest.fail(function (e) { console.log(e); }); 

And i am just doing var_dump($_REQUEST) at json_handler.php and ajax request is keep failing and get nothing in response text

When i tried

$json = file_get_contents('php://input');
var_dump($json);

I got the json but ajax request is still failing.

I have also tried to do this javascript and my code is below

var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = stateHandler;
httpRequest.open("POST", "json_handler.php", true);
httpRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpRequest.send( JSON.stringify(dummyData ));

Here is my console log

在此输入图像描述

See because your ajax is having dataType: "json" so it is expecting the response in json format which is like {key:value} or [{k:v}, {k:v}, ....] and you are not echo ing any json structure so this is where your ajax is failing.

Seems to me you have to write it this way:

$json = file_get_contents('php://input');
echo json_encode($json);

Your request seems good, but why do you stringify your JSON?

You can post payload data:

data: dummyData

To debug and test your json post, you can use extensions as Postman or Advanced Rest Client.

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