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!');;
1

1 Answer 1

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'];
Sign up to request clarification or add additional context in comments.

4 Comments

Note for the OP: It will "autodetect" the dataType value if not provided, but I personally prefer to specify it.
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?
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.