I want to send json data to ajax but how do you convert variables into json or convert an 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");
}
});
});
If you really want to convert the data into JSON, you have to create an object or array and use
JSON.stringify(available in newer browser and can be loaded form here):but you cannot just set the
dataattribute tofthen. You have to assign it to another variable:This will produce the POST parameters like so:
However, there is not reason to create JSON here. I would sent the values as normal post parameters. For that you just create an object like above and assign it to
data:This will create the POST parameters:
This would be easier as you don’t have to parse the JSON at the server side.