1

*Hi , I am very new to using JSON in Jquery. I have a html form which made out using json data and javascript. The Json string is holding the result. Now my question is how to send this string to php file. I am using ajax function for submitting the form * this is the json string i have

 var jsonstr = JSON.stringify(result);

 $.ajax({ type:"POST",
              url: "ajax.php",
              headers: {
                  'Content-Type': 'application/json',

              success: function(){
                  alert('Test results submitted!');;
cherry
  • 13
  • 1
  • 5

1 Answers1

4

Specify the data and dataType options:

var jsonstr = JSON.stringify(result);

$.ajax({ 
          type:"POST",
          url: "ajax.php",
          data:'json=' + jsonstr,
          dataType:'json',
          success: function(){
              alert('Test results submitted!');
          }
});

From php, you can get json string using:

$_POST['json'];
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Note for the OP: It will "autodetect" the `dataType` value if not provided, but I personally prefer to specify it. – Jared Farrish Feb 11 '12 at 09:36
  • Also, should the data be stringified before being handed to `$.ajax()`? Is `data:` needed if the data is just the form data? Won't jQuery automatically stringify the data from the form? – Jared Farrish Feb 11 '12 at 09:41
  • @JaredFarrish: It is specified explicitly so that one could get its value from php using `$_POST['json'];`. If this is skipped, data can still be gotten through `php://input`. So this is matter of choice but later option is unknown to most newbie devs. In this case OP also stores whole stuff in `jsonstr` var which should be forwarded. – Sarfraz Feb 11 '12 at 09:45
  • Ok, I was under the impression that it needed to be an object. `dataType` is perhaps misleading as well, which I noticed looking at the `data:` you have; that's the beginning of a query string key/value, correct? `dataType:` refers to the response (which may not be JSON). `data:` needs to be a string that's serialized, but is not specifically related to the response `dataType`. – Jared Farrish Feb 11 '12 at 09:52