theQman theQman - 4 months ago 11
jQuery Question

'Undefined' when trying to access json response

My flask app has code that returns the following:

return json.dumps({'status': 'OK','url': 'www.blahg.com'})


My javascript code looks like this:

$(function() {
$('#mainbutton').click(function() {
$.ajax({
url: '/buttonclick',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
console.log(response.url);
},
error: function(error) {
console.log(error);
}
});
});
});


The first console log looks correct:
{"status": "OK", "url": "www.blahrg.com"}
, but when I try to access the
url
entry, I get 'undefined' as output. what am I doing wrong?

Answer

You can also use dataType to have jQuery parse it for you:

$(function() {
  $('#mainbutton').click(function() {
        $.ajax({
            url: '/buttonclick',
            data: $('form').serialize(),
            type: 'POST',
            dataType: 'json', // this bit here
            success: function(response) {
                console.log(response);
                console.log(response.url);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });
});
Comments