Sheldon
Sheldon

Reputation: 10077

Why can't I append to my JSON object? (jQuery/Javascript)

I'm using the following code in an attempt to add a new attribute to bar object:

$(document).ready(function(){
    $('form').on("submit",preventDefault);
});

function preventDefault(e) {
    e.preventDefault();
    $url="contact/send";
    bar = $('form').serialize();
    bar["foo"]='xyz';
    //bar.foo="123";
    console.log(bar);
}

However I don't ever seem to get the value of bar.foo. If I look at the console in Chrome I always get a result similar to this:

name=Grahame&email=foo%40bar.com&message=Hello.

Why am I not getting the value/property of foo?

Upvotes: 0

Views: 191

Answers (4)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

Other answers here talk about how one might get around this, but no one is explaining why this is happening, so I figured I'll give it a shot.

Here is what is happening in the background:

  • You call .serialize which produces a string

  • Strings in JavaScript are primitive value types, so when you add a property to it, it "autoboxes" becomes a String reference type object for that call.

  • You assign the property to it, which is added to the boxed object

  • console.log(bar); logs the bar object, which is already again a string which is a primitive value type. Both because toString of the String type, and because of the bar being a primitive value type, you get the same initial value.

You can read more about this in the secret life of primitives in JavaScript. Or in the specification

How to fix it

See How to add a value to jQuery serialize . That has already been answered there.

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

change to:

bar = $('form').serializeArray();
bar["foo"]='xyz';

Upvotes: 0

Quentin
Quentin

Reputation: 943142

bar is serialized form data. It is a string not an object.

If you want to add data do it you need to serialize that data:

bar += "&" + encodeURIComponent('foo') + "=" + encodeURIComponent('xyz');

(You can skip the encode URI components if you know that the data has no URL special characters in it).

Upvotes: 0

Joe
Joe

Reputation: 15528

You can just use this:

bar = $('form').serialize();
bar += '&foo=xyz';
console.log(bar);

Currently you're trying to use bar as an array (or an object in your commented code). .serialize() actually generates a URL-ecoded string so you can simply append your value to it.

Upvotes: 0

Related Questions