1

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
    }

    });
8
  • what file do you have the print_r statement in? your page that contains the javascript or the page that is called by the javascript (generateBing.php)? Commented Apr 29, 2012 at 0:40
  • Why do you have dataType: "html"? Commented Apr 29, 2012 at 0:41
  • generateBing.php isn't related. getNum.php contains the print_r code Commented Apr 29, 2012 at 0:41
  • @Shedal because the getNum.php script returns html Commented Apr 29, 2012 at 0:41
  • How about print_r($_POST)? I guess it will contain two keys: id and nameList. Commented Apr 29, 2012 at 0:45

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I doubt jQuery will handle posting hierarchical data.
You'll want to remove contentType, since this way stops it from being application/json.
@loganfsmyth - removed both, as they are normally not needed. If it's a valid json object, jQuery will figure it out.
0

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);

1 Comment

There, should work now. As you mentioned, the contentType effects all of this. Since you had JSON content-type, PHP cannot automatically process it. It is up to you to read the request data and process it into PHP vars.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.