0

I am trying to pass a JSON object to a PHP page, this is my jquery script.

        reg_id   = $('#registroid').val();
        razonid = $("#selectRazonId").val();
        $.ajax({
            data: JSON.stringify({myData:{razonid:razonid,reg_id:reg_id}}),
            type: "POST",
            dataType: "json",
            url: "inc/sitctp0013Procesa-2.php",
            contentType: "application/json; charset=utf-8",
            success: function(data){ 
                alert(data);
            }
        });

And this is my PHP script

 <?php
 $myPostData = json_decode($_POST['myData']);
 $firstname = $myPostData["razonid"];
 $lastname = $myPostData["reg_id"];
 if($myPostData){
        echo "good";
 } else{
    echo "bad";
 }
 ?>

but is only printing "bad", I tried doing a var_dump($_POST); but I'm getting a null result.

If I look at the firebug console I can see that the JSON object it is being sent

https://i.sstatic.net/9aQ5o.jpg

2
  • jQuery handles encoding the data for you. You don't need to use JSON.stringify, drop that part. It should just be data: { myData: { ... } }. You also don't need the contentType option. Commented Jul 30, 2014 at 18:34
  • @meagar if I remove the stringify, the object is sent like this "myData%5Brazonid%5D=3&myData%5Breg_id%5D=70212" and still not working Commented Jul 30, 2014 at 18:37

2 Answers 2

1

The default return value of json_decode() is an object - if you want an associative array, you'll need to pass true as the second parameter.

$myPostData = json_decode(file_get_contents('php://input'), true);
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! this is what I was missing, I couldn't find anything related to the file_get_contents while I was researching.
0

You're double json-encoding your data. You've already told jquery that you're sending/receiving JSON, yet are encoding your object data to json yourself.

Jquery has absolutely NO way of telling that the string coming out of JSON.stringify is actually json. It never sees that json.stringify was actually called. It just sees a string, and re-encodes it again, so your

{"myData":.....}

string comingo out of the stringify call will be turned into

"{\"myData\":.....}"

All you need is:

 data: {myData:.....}

Comments

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.