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");
}
});
});
String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.
Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.
JS Array to JSON using JSON.const jsonString = JSON. stringify([1, 2, 3, 4, 5]); The JSON. stringify() method converts a JavaScript object, array, or value to a JSON string.
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):
var f = JSON.stringify({street: street, location: location, number: number});
but you cannot just set the data
attribute to f
then. You have to assign it to another variable:
data: {data: f}
This will produce the POST parameters like so:
data={"number":"value of number","location:...}
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
:
data: {street: street, location: location, number: number}
This will create the POST parameters:
street=valueofstreet&location=valueoflocation&...
This would be easier as you don't have to parse the JSON at the server side.
If you want to send a JSON formatted request to the server you could specify the proper 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 in the POST body:
{ street: 'foo', location: 'bar', number: 'baz' }
Obviously the server side script you are sending this AJAX to need to be capable of handling and parsing JSON strings.
var f = {}
f['street'] = $("#street").val();
f['location'] = $("#location").val();
f['number'] = $("#number").val();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With