gogo_rulez
gogo_rulez

Reputation: 389

jquery ajax call returns object, how to get object value

So our programmer did an AJAX call that returns an object. I don't have a clue how to append the data it return to an element. Any help is appreciated.

AJAX CALL

$('.submit_btn').unbind('click').bind('click', function(e) {
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: $(this).data('url'),
        data: {
            csrfmiddlewaretoken: $(this).data('csrf')
        },
        success: function(data) {
            console.log('success');
            console.log(data);
        },
        error: function(ret) {
            var data = JSON.parse(ret.responseText);
            console.log('error');
            console.log(data);
        },
    });
});

After clicking the submit button, I get in the console "success" and:

Object {409: "Response message"} or Object {201: "Response message"}

And i should append the response message to an element. How can i access the response message?

Upvotes: 2

Views: 12657

Answers (4)

Jack jdeoel
Jack jdeoel

Reputation: 4584

Try this code

success: function(data) {
        if(data["409"]){        
        console.log(data["409"]);
        }
        else{
        console.log(data["201"]);        
        }
    }

Upvotes: 0

Peter
Peter

Reputation: 6669

Since you don't always know the key returned (409 or 201), you can retrieve the response message of the data by doing:

data[Object.keys(data)[0]]

It will give you access to data[409] or data[201]

Upvotes: 1

user5311329
user5311329

Reputation:

success: function(data){
  var obj = jQuery.parseJSON(data);
  console.log(obj['yourfieldname_in_json']);
}

Upvotes: 4

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

console.log(data["409"]);

Upvotes: 1

Related Questions