Reputation: 1951
this is probably something very simple to fix. Im posting to a php page that returns the ID of the new element created in the db- (posting via $.ajax
)- i have logged the returned value.
The following code is the code i use to post
$.ajax({
type: "POST",
url: "<?=base_url()?>events/add_tag_js/",
data: url,
success: function(html){
$("#tag_list").append('<li><span id="" class="tag">'+formvalue+'<span class="remove_tag"><a class="remove_tag_link" href="#">x</a></span></span></li>');
$("#add_tag").val('');
console.log(html);
},
failure: function(){
$('.error').show();
$("#add_tag").val('');
}
});
The return value from the console.log is
{"error":false,"msg":"Tag added","id":44}
but when i do alert(html.id)
i get undefined? do i need to parse the json returned to do this? or is my json incorrect?
Upvotes: 0
Views: 408
Reputation: 915
Try to tell it to handle it as Json, in your case the html is a String, so you would have to to an var myObj = eval(html); which is bad
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
Upvotes: 0
Reputation: 1038730
Maybe you didn't set the proper content type on your server side script, so jQuery doesn't know that this is JSON. So either set the content type to application/json
on your server script or you could also indicate that you expect JSON in the request using the dataType
parameter:
...
type: "POST",
url: "<?=base_url()?>events/add_tag_js/",
data: url,
dataType: 'json', // indicate that you expect JSON from the server
...
Although it is recommended to have your server side script set the proper content type.
Upvotes: 2