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?

JavaScript

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):

JavaScript

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

JavaScript

This will produce the POST parameters like so:

JavaScript

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:

JavaScript

This will create the POST parameters:

JavaScript

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