views:

162

answers:

4

Hi Gurus

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!

+2  A: 

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'];
Justin Ethier
Hi Justin, thanks but I get nothing with this =/
Curro
Hmmm. Have you tried using firebug to see what is actually sent in the POST request?
Justin Ethier
Also, why are you saying `contentType: "application/json; charset=utf-8",` instead of `contentType: `"application/json"`
Justin Ethier
+1  A: 

You're not decoding JSON on PHP-side.

Try json_decode

dare2be
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.
Justin Ethier
A: 

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']);
    
Felix Kling
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?
Curro
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.
Curro
Finally made it work, your comments were very useful!
Curro
A: 

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.

Curro