Reputation: 1780
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?
Upvotes: 2
Views: 15290
Reputation: 21684
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);
}
});
});
});
Upvotes: 6
Reputation: 3227
You haven't parsed the JSON:
success: function(data) {
var response = JSON.parse(data);
console.log(response);
console.log(response.url);
}
Upvotes: 7