2

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?

4
  • console.log(data.409); Commented Sep 18, 2015 at 9:41
  • the data that was send from php is data since you didnt specify the data type type you should parse it Commented Sep 18, 2015 at 9:41
  • @DavidJawphan That's completely wrong, did you even test it? Use data[409]. Commented Sep 18, 2015 at 9:43
  • data[409] works, but sometimes it returns 409: "response message" and sometimes it returns 201: "response message".... Commented Sep 18, 2015 at 9:48

4 Answers 4

4
success: function(data){
  var obj = jQuery.parseJSON(data);
  console.log(obj['yourfieldname_in_json']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

console.log(obj['409']);
you can also do this to access value console.log(obj[0][0]);
please add a brief description as to how this resolves the askers problem. Welcome to Stack Overflow, recommended reading How to Answer.
1

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]

2 Comments

give us more explanation about this line @peter, It works perfectly but i dont know how
Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually. Culled from developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
1

Try like this

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

Comments

0

Try this code

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

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.