6

I'm facing the problem of receiving an empty array when I do an AJAX request in the following way:

This is the code I'm executing in JavaScript:

  <script type="text/javascript" src="lib/jquery.js"></script>
  <script type="text/javascript" src="lib/jquery.json.js"></script>
  <script type="text/javascript">   
   $(document).ready(function(){

    /* Preparar JSON para el request */
    var mJSON = new Object;
    mJSON.id_consulta = new Array;
    for (var i=0; i<3; i++){
     mJSON.id_consulta[i] = new Object;
     mJSON.id_consulta[i].id = i;
    }
    var sJSON = $.toJSON(mJSON); 

    $.ajax({
     type: "POST",    
     url: "getUbicaciones.php",  
     data: sJSON, 
     dataType: "json", 
     contentType: "application/json; charset=utf-8",              
     success: function(respuesta){  
      alert(respuesta);
     },
     error: function (request,error){
      alert("Error: " + request.statusText + ". " + error);
     }
    });  

   });
  </script>

And this is the code under PHP:

 <?php 
 /* Decodificar JSON */
 $m_decoded = $_POST;

 print_r($m_decoded);
 exit;
 ?>

And all I get from this, using Chrome's Developer Tools is an empty array:

Array
(
)

Any clues on what am I doing wrong?

The string sJSON is being encoded correctly, this is what I get when I do an "alert" on that one:

{"id_consulta":[{"id":1},{"id":2},{"id":3}]}

Thank you everyone in advance!

4 Answers 4

2

From your JavaScript, you need to pass the data like this, as key-value pairs:

data: {"mydata" : sJSON},

On the PHP side, since $_POST is an associative array you can then access your data like so:

$m_decoded = $_POST['mydata'];
Sign up to request clarification or add additional context in comments.

4 Comments

Hmmm. Have you tried using firebug to see what is actually sent in the POST request?
Also, why are you saying contentType: "application/json; charset=utf-8", instead of contentType: "application/json"`
Actually you need not specify contentType, since what you are going to post is a serialized json array which ultimately will get converted into key value pair string (jquery does it internally), contentType is used to tell what kind of data you are sending... in this case json will be converted into key value pair and will be send in a plain string... dataType: 'json' is more than enough for it to work
if you read this link jquery ajax Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
1

You're not decoding JSON on PHP-side.

Try json_decode

1 Comment

Yes, but in his example I think he was just pointing out that the $_POST array was empty. Presumably once the data is received he would need to use json_decode to do something useful with it.
0

There are several issues in your code:

  1. You are declaring dataType: "json" but the server does not return JSON, it returns plain text. From the documentation:

    The type of data that you're expecting back from the server. If none is specified, jQuery will intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

  2. I don't think that jQuery can successfully transform your data to a query string. You are trying to send an array of objects:

    {"id_consulta":[{"id":1},{"id":2},{"id":3}]}
    

    Use Firebug and examine which data is actually sent. If you want to send the whole string as JSON, you have to set the processData option to false:

    $.ajax({
       type: "POST",    
       url: "getUbicaciones.php",  
       data: "json=" + $.toJSON(mJSON.id_consulta), 
       processData: false,
       //....
    

    and you have to decode the string on the server side:

    $data = json_decode($_POST['json']);
    

2 Comments

Thank you for your quick response Felix, but I think that didn't work, I changed my ajax request to this: $.ajax({ type: "POST", url: "getUbicaciones.php", data: "json=" + $.toJSON(mJSON.id_consulta), processData: false, success: function(respuesta){ alert("Success:" + respuesta); }, error: function (request,error){ alert("Error: " + request.statusText + ". " + error); } }); And in PHP I did this: $m_decoded = json_decode($_POST["json"]); But the result is now empty, $m_decoded is empty, any other clues?
I'm receiving this in PHP (json encoded): [{\"id\":0},{\"id\":1},{\"id\":2}] and the try to decode with json_decode, it returns "empty". I'm trying this: $m_decoded = json_decode($_POST["json"]); and the result is nothing.
0

Finally made it work!. It went like this:

JavaScript:

var sJSON = $.toJSON(mJSON.id_consulta);


            $.ajax({
                type: "POST",    
                url: "getUbicaciones.php",  
                data: "json=" + sJSON,                  
                processData: false,             
                success: function(respuesta){       

                },
                error: function (request,error){

                }
            }); 

PHP:

$m_decoded = json_decode(stripslashes($_POST["json"])); 

Note that I had to use "stripslashes" since the JSON string had slashes for the " character.

Thank you everyone for all your help, I hope this helps someone else.

1 Comment

Well it worked, but you could have simply said data: mJSON and no need to mention processData, also no need to convert it into JSON with var sJSON = $.toJSON(mJSON.id_consulta);. You could have simply written data:mJSON and remove processData parameter.... At PHP end you would directly get a array which you need not decode nor stripslash

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.