tags:

views:

990

answers:

7

Hi All:

Currently I am working on a ajax-based web application that does some XHR.

I chose CakePHP + jQuery to do the jobs, they work pretty well except this little problem.

Say, I make a String of a valid JSON form ==> { "test" : "hello world"}

Then I am calling jQuery's ajax method to send it to the destination php page:

jQuery.ajax
    ({
        type: 'POST',
        cache: false,
        async: false,
        timeout: 10000,
        url : 'http://localhost/method/',
        dataType : 'json',  //defines expected response datatype
        contentType : 'application/json', //defines request datatype
        data : { "test" : "hello world"},
        success : function(json)
        {
           //do some stuff here.
        }});

Previously I tried this ajax function with empty data (i.e. just use data : {} since this is a POST), and it worked just fine; however, now that I've added a json-formatted data to the HTTP POST, is there a way to refer to it from the PHP script's side?

I tried : data : { "data" : {"test" : "helloworld"}}

I use PHP's isset[$_POST['data'] to check, and the result is POST variable 'data' is unset.

Can anyone give me a way to solve this problem? Many thanks in advance!!!

A: 

The data will come in to PHP in the key/value format normally associated with a POST request. The jQuery data value is just what jQuery uses to create the POST request... the actual key/value pairs that go into PHP's $_POST array are what you put inside data.

For your code, you should have a $_POST['test'] value of helloworld.

zombat
Hello zombat:Yeah I've tried that as well. But I still have an unset $_POST['test']from the PHP side. This is also checked in the FireBug console...Puzzled :(
Michael Mao
A: 

Each key/value pair in the data array is sent to PHP as a POST key/value pair. So in your case:

echo $_POST['test']; // Echos "helloworld"
James Skidmore
A: 

looks like the url may have been spelt incorrectly?

url : 'http://localhost/mehtod/'

instead of

url : 'http://localhost/method/'

Sometimes the smallest things are the most annoying!

Hello dspinozzi:No, that's just a fake method name, typed so fast that it looks like a typo...Actually the real scenario is more complicated. I just made up such a small example to be part of a good question :)Thanks for your keen checking! Already edited on my initial post.
Michael Mao
A: 

Im not sure if setting the content type has any implications with cake php.

http://docs.jquery.com/Ajax/jQuery.ajax#options

When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.

by setting it to application/json may be encoding it different, and thats why your not seeing it in the $_POST array

Hi dspinozzi:I can run both jQuery and PHP with no problem if I remove the contentType option and keep my data as data : "test=blahblahblah"But that's not what I want...I want to figure out a way so that I can construct a json-formatted string before sending it to the PHP script page where it would be decoded using PHP's json_decode method to retrieve its content as asso-array.
Michael Mao
+4  A: 

This may be what you are after (from http://www.factsandpeople.com/facts-mainmenu-5/26-html-and-javascript/89-jquery-ajax-json-and-php):

$(document).ready(function(){ 
  var data = 
  { 
    "sales": [ 
      { "firstname" : "John", "lastname" : "Brown" },
      { "firstname" : "Marc", "lastname" : "Johnson" }
    ] // end of sales array
  }
  var dataString = JSON.stringify(data);
  $.post('simpleformSubmit.php', { data: dataString}, showResult, "text");
});

The PHP script (Post data contains a json structure):

<?php
  $logFile = 'logFile';
  $res = json_decode(stripslashes($_POST['data']), true);

  echo "sales1_lastname: ".$res['sales'][1]['lastname'];
?>
Hi dspinozzi:Thanks for your help! I will do it this way.
Michael Mao
A: 

Hi there,

a quote from the jQuery docs (http://docs.jquery.com/Ajax/jQuery.ajax#options):

data - 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 i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

bjoernwibben
A: 

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{Values:["1","2","3"]}

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

DustinDavis