Skip to content
Advertisement

How to convert variables into json?

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");
            }
            });
});

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement