0

I'm using bootstrap 3 and jquery to develop my app. My question is, why i got null object if not using JSON.stringify instead formValues?

Before using JSON.stringify

var that = this;
var formValues = {
    userId: 315,
    locale: "en",
};
this.collection.fetch({
    type: "POST",
    contentType: 'application/json',
    dataType: "json",
    data: formValues,
    success: function(collection, response) {
        var template = _.template(accountsSummaryTemplate, {
            accounts: that.collection.models
        });
        that.$el.html(template);
        console.log(that.collection);
    },
    error: function(collection, response) {
        console.log(that.collection);
    }
});

After using JSON.stringify

var that = this;

function formToJSON() {
return JSON.stringify({
    "userId": 315,
    "locale": "en",
});
}
this.collection.fetch({
    type: "POST",
    contentType: 'application/json',
    dataType: "json",
    data: formToJSON(),
    success: function(collection, response) {
        var template = _.template(accountsSummaryTemplate, {
            accounts: that.collection.models
        });
        that.$el.html(template);
        console.log(that.collection);
    },
    error: function(collection, response) {
        console.log(that.collection);
    }
});

Thanks a lot in advance.

3 Answers 3

1

If the data property is an object, jQuery serializes it with $.param:

> $.param({userId: 315, locale: "en"});
"userId=315&locale=en"

If you pass in a string instead, jQuery doesn't serialize it. Look at the requests using your web browser's developer tools.

Sign up to request clarification or add additional context in comments.

Comments

0

Because that's not a proper data string.

 var formValues = "userid=5&locale=en";

Comments

0

Because JS object is not JSON. JSON is string, JS object is an object. If fetch uses jQuery.ajax, it expects either a JS object, or a query string (which is not JSON): "userId=315&locale=en".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.