Anand Jose
Anand Jose

Reputation: 658

Add JavaScript object to form data while submit the form

The user has the option to perform several actions in the form, after action when he submits the form, needs to add a JavaScript object to form. I tried multiple ways, in server data reached as [Object object]

JavaScript Object

var damageitems = {'5b3b43285d57025915000002':
                  {action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
                  }

Script I tried

$( "form" ).submit(function( event ) {
        event.preventDefault();
        url = $(this).attr( "action" );
        var postData = $(this).serializeArray();
        postData.push({name: 'damage_items', value: damage_items});
        $.post(url, postData, function(){});
    });

Value reached in server

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"uztc+G0fyTb8wH7D6HZAslTfxuJvFLP3UunjiRjWylk=", "damage_items"=>"[object Object]", "action"=>"batch_update", "controller"=>"damage_items", "claim_id"=>"5b3b41415d57026665000001"}

My aims submit the value as normal submit not ajax, the value in js variable reaches in the server as a hash with key damage_items. Not prefer the way add it in form control value then submit

Upvotes: 1

Views: 5460

Answers (2)

Emeeus
Emeeus

Reputation: 5250

The best way is to turn a JavaScript Object Literal into a JSON (see the differences here). Because It is easy for machines to parse and generate and most of server side languages have methods to parse it. Also in http requests, like ajax, we must send strings.

Fortunately we have a method in js to do that, and is using JSON.stringify() and a method to turn a JSON into JavaScript Object Literal using JSON.parse()

Then, in your code:

//JavaScript Object Literal
var damageitems = {'5b3b43285d57025915000002':
                  {action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
                  }


damageitems = JSON.stringify(damageitems);


//JSON - It is easy for machines to parse and generate
// we could put this in a request because it's a string,
console.log(damageitems);

Upvotes: 1

Aayush Sharma
Aayush Sharma

Reputation: 849

Updating your script to the following will do the trick

$( "form" ).submit(function( event ) {
    event.preventDefault();
    url = $(this).attr( "action" );
    var postData = $(this).serializeArray();
    postData.push({name: 'damage_items', value: JSON.stringify(damage_items)});
    $.post(url, postData, function(){});
});

When you try to store the data in the form, it is converted into a string using toString method if it is not a string already. toString method of Object returns [object Object] and that is why you are getting it.

Converting it into a JSON string will prevent that.

Upvotes: 2

Related Questions