I have one form which uses to POST form data in JSON key value pair to URL. Same as below format:

[{'name': 'URL', 'value': 'http://127.0.0.1:8000/test/addcustomer'}, {'name': 'FirstName', 'value': 'Abc'}, {'name': 'LastName', 'value': 'Xyz'}, {'name': 'DOB', 'value': '123457'}, {'name': 'EmailAddress', 'value': '[email protected]'}, {'name': 'Address1', 'value': '123 Street'}, {'name': 'Address2', 'value': '11123'}, {'name': 'City', 'value': 'Xyz'}, {'name': 'State', 'value': 'Pqr'}, {'name': 'PostalCode', 'value': '12345'}]

Instead of this I want something like below:

[{'URL':'http://127.0.0.1:8000/test/addcustomer', 'FirstName':'Abc','LastName': 'Xyz','DOB':'123457', 'EmailAddress':'[email protected]','Address1': '123 Street','Address2':'11123','City':'Xyz','State':'Pqr','PostalCode':'12345'}]

Please refer below code:

$(document).ready(function(){
    $("#submit").on('click', function(){
     var a=document.forms["myForm"]["EmailAddress"].value;
     var b=document.forms["myForm"]["URL"].value;
        if (a==null || a=="" || b==null || b=="")
        {
            $("#EmailAddress").css("border-color", "#963634");
            $("#URL").css("border-color", "#963634");
            alert("Please fill Email Address and URL!!!");
            return false;
        }
        else
        $.ajax({
            url: b, 
            type : "POST",
            data : JSON.stringify($("#myForm").serializeArray()), 
            success : function(result) {
                alert(result);
                $("#myForm")[0].reset();
            },
            error: function() {
                alert('Please enter valid URL');
            }
        })
    });
});

1 Answers

0
infogulch On

I would try something like:

        else
        {
            let formData = $("#myForm").serializeArray();
            let data = formData.reduce((acc, x) => acc[x.name] = x.value, {});
            $.ajax({
                url: b, 
                type : "POST",
                data : JSON.stringify(data), 
                success : function(result) {
                    alert(result);
                    $("#myForm")[0].reset();
                },
                error: function() {
                    alert('Please enter valid URL');
                }
            })
        }

The reduce line is roughly equivalent to:

// formData is in the form [ {'name': 'A', 'value': B}, {'name': 'X', 'value': Y},... ]
let data = {};
for (let item of formData)
    data[item.name] = item.value;
// data is now in the form { 'A': B, 'X': Y, ... }