Javascript callback with AJAX + jQuery
Posted
by
Fred
on Stack Overflow
See other posts from Stack Overflow
or by Fred
Published on 2010-12-24T05:52:19Z
Indexed on
2010/12/24
5:54 UTC
Read the original article
Hit count: 287
Hey!
I have this jQuery code
(function () {
function load_page (pagename) {
$.ajax({
url: "/backend/index.php/frontend/pull_page/",
type: "POST",
data: {page: pagename},
success: function (json) {
var parsed = $.parseJSON(json);
console.log(parsed);
return parsed;
},
error: function (error) {
$('#content').html('Sorry, there was an error: <br>' + error);
return false;
}
});
}
...
var json = load_page(page);
console.log(json);
if (json == false) {
$('body').fadeIn();
} else {
document.title = json.pagename + ' | The Other Half | freddum.com';
$("#content").html(json.content);
$('#header-navigation-ul a:Contains('+page+')').addClass('nav-selected');
$('body').fadeIn();
}
})();
and, guessed it, it doesn't work. The AJAX fires fine, the server returns valid JSON but the console.log(json);
returns undefined
and the js crashes when it gets to json.pagename
.
The first console.log(parsed)
also returns good data so it's just a problem with the return
(I think).
I knew I was clutching at straws and would be extremely if this worked, but it doesn't. To be honest, I don't know how to program callback functions for this situation.
Any help is greatly appreciated!
© Stack Overflow or respective owner