david
david

Reputation: 1077

Convert form data to json before sending with ajax

I am trying to convert form data to JSON to be sent using Jquery. I understand that this has been asked many times on SO, so far this is the best answer I have found

https://stackoverflow.com/a/11339012/492015

Answer from link above

function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

Usage:

var $form = $("#form_data");
var data = getFormData($form);

However this is producing invalid JSON according to https://jsonlint.com also Spring Boot is not accepting it as valid JSON since there are no double quotes around comment and country

{comment: "This is a comment", country: "us"}

Is there a simple way to convert form data to valid JSON? I am trying to generate the following JSON format

{"comment": "This is a comment", "country": "us"}

Upvotes: 2

Views: 456

Answers (1)

Robin Mollah
Robin Mollah

Reputation: 128

The following is a Javascript Object. It is not JSON. To convert it to JSON, you can use JSON.stringify(object) function.

{comment: "This is a comment", country: "us"}

Here is an example how to convert a JavaScript object to JSON.

let jsObject = {comment: "This is a comment", country: "us"};

document.write(JSON.stringify(jsObject));

Upvotes: 3

Related Questions