简体   繁体   中英

jQuery AJAX PHP JSON problem

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!

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'];

You're not decoding JSON on PHP-side.

Try json_decode

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM