Tom
Tom

Reputation: 9663

How to parse json data received from a jQuery ajax call in php

I'm calling a php script (getNum.php) via ajax after creating an object and using jquery.json to turn it to json. Now i want to handle the object on the php side. print_r($_POST['data']) doesn't work nor anything else i've tried.

This is my code:

// create object
    var bing= new Object();
    bing.id = 99;
    bing.nameList = getBingList();

    //create pdf
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "getNum.php",
    dataType: "html",
    data: $.toJSON(bing),
    success: function(data){
        alert(data);
        window.location = "generateBing.php?num="+data
    }

    });

Upvotes: 1

Views: 4004

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161677

Since you are posting a JSON object directly, there is no argument name for $_POST. You'll need to read the raw contents of the POST request. Try this:

$data = json_decode(file_get_contents('php://input'));
print_r($data);

Upvotes: 0

adeneo
adeneo

Reputation: 318372

If you're using print_r($_POST['data']) to show the content, you'll need to send it as "data" as well.

$.ajax({
    type: "POST",
    url: "getNum.php",
    data: {data: $.toJSON(bing)},
    success: function(data){
        alert(data);
        window.location = "generateBing.php?num="+data
    }
});

Otherwise you have to do print_r($_POST)

Upvotes: 2

Related Questions