Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

enter image description here

like image 976
Richerd fuld Avatar asked Aug 02 '26 13:08

Richerd fuld


1 Answers

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 echoing 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);
like image 194
Jai Avatar answered Aug 05 '26 06:08

Jai