Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 288
Arturo Avatar asked May 14 '10 16:05

Arturo


1 Answers

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'];
like image 173
Justin Ethier Avatar answered Oct 07 '22 14:10

Justin Ethier