Hi I need to build data in a JSON object and send through a ajax post, as a String.
I need to send something in the following format:
{
"myRequest": {
"myRequestType": "updateStatus",
"fields": [
{
"item1": "data1",
"item2": "data2",
"item3": "data3",
"formUpdateField": "data4"
}
]
}
}
I have a form table, which has a checkbox to select record(s) to send the update for. basically the send is to update a status of a record.
Based on the above, I have access to item1, item2 and item3 data – this is non form data. I need to add this to a JSON object. I think I can just about do this. But my problem is, I need to then add the data that I have from the form too, to this JSON Object.
I am able to get the data out of the form, but how to I add this to the JSON object I am building up?
The other issue is that, you can select multiple records from the form table
Any ideas how I can do this using JSON/jQuery etc?
Build your object as an object, then stringify it later. It’s far harder to string-handle a JSON string together yourself than it is to stringify later.
If you’re happy to support modern browsers only, you can take advantage of the native
JSON.stringify()method that arrived in ECMA5. If not, there are plenty of third-party scripts that do the same thing.Try this:
HTML (simple form)
JS
That will iteratively append the fields and their values to your object, then stringify it when sending it as part of the AJAX request.
Finally, couldn’t your
fieldsdefinition be just an object, rather than an array whose existence is purely to house the inner object? Seems needless, but perhaps there’s more to your data structure than you’ve shown.