How to convert variables to json?

I want to send json data to ajax, but how to convert variables to json or convert array to json?

$(".confirm_order").click(function(event) { event.preventDefault(); var street = $("#street").val(); var location = $("#location").val(); var number = $("#number").val(); var f = ??? $.ajax({ type: 'post', url: "/orders", dataType: "json", data: f, success: function (l) { alert("Done"); } }); }); 
+4
source share
6 answers

If you really want to convert the data to JSON, you need to create an object or array and use JSON.stringify (available in a new browser and you can download the form here ):

 var f = JSON.stringify({street: street, location: location, number: number}); 

but you cannot just set the data attribute to f . You must assign it to another variable:

 data: {data: f} 

This will result in the following POST parameters:

 data={"number":"value of number","location:...} 

However, there is no reason to create JSON. I would send the values ​​as normal message parameters. To do this, you simply create an object, as described above, and assign it data :

 data: {street: street, location: location, number: number} 

This will create the POST parameters:

 street=valueofstreet&location=valueoflocation&... 

It will be simpler since you do not need to parse JSON on the server side.

+8
source

If you want to send a formatted JSON request to the server, you can specify the correct content type for this request, and then use the JSON.stringify method:

 var street = $('#street').val(); var location = $('#location').val(); var number = $('#number').val(); $.ajax({ type: 'post', url: '/orders', dataType: 'json', data: JSON.stringify({ street: street, location: location, number: number }), contentType: 'application/json; charset=utf-8', success: function (l) { alert("Done"); } }); 

This will send the following to the POST body:

 { street: 'foo', location: 'bar', number: 'baz' } 

Obviously, on the server side of the script, you are sending this AJAX so that it can process and parse JSON strings.

+3
source
  var f = {} f['street'] = $("#street").val(); f['location'] = $("#location").val(); f['number'] = $("#number").val(); 
+1
source
 var f = { "street": street, "location": location, "number": number }; 
0
source

Use JSON.stringify from json2.js

Remember to specify contentType: 'application/json' in your configuration file.

0
source

try it. values ​​will be replaced accordingly

{street : street,location : location, number : number}

0
source

All Articles