Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone save does not send undefined attributes

Tags:

backbone.js

I have the following code :

     this.myModel.save(this.patchAttributes, {
        //Ignored if saving new record; will send a POST
        patch: true,
        success: function() {
               success();
            }
        },
        error: function() {
                error();
        }
    });

If my patchAttributes has an entry like fieldName:undefined, I cannot see it in the request headers of the PATCH request.

like image 620
budhavarapu ranga Avatar asked Feb 02 '26 18:02

budhavarapu ranga


1 Answers

That's because Backbone is JSON.stringifying the data before sending it. The JSON spec does not allow the undefined token. Therefore any properties that are undefined will be omitted from the JSON string.

JSON.stringify({ foo: undefined });
// The output is "{}"

Instead of undefined you should use null which is part of the JSON spec:

JSON.stringify({ foo: null });
// The output is "{"foo":null}"
like image 181
idbehold Avatar answered Feb 04 '26 15:02

idbehold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!