I have 2 javascript functions, the first being a function which loads ajax content (via another function), and a second which is a callback function. They look like:
function createReply(callBack){
ajaxPage('test.html', 'next-reply');
callBack();
}
function updateNext(){
document.getElementById('next-reply').id = "reply-item";
}
createReply(updateNext);
As you can see, I am calling the createReply()
function and passing it the name of the callback function, in this case updateNext()
In the createReply()
function, I am calling another function which loads content via ajax. When this function is complete, the callback is supposed to be executed. The callback changes the id of the div in which the ajax content is being loaded. This is where the problem is occuring
I am getting the error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
Which is saying that it cannot change the content of the element with the id "next-reply" because it doesn't exist, and the reason it doesn't exist is because the callback function changes the id if that element. The intention is to have the callback fire after the ajax content has been loaded (ie; after the ajaxPage()
function has been executed)
Can anyone see what the problem is? Is there a better way of implementing a callback function in plain javascript?
PS: no jQuery
Right now you callback is executed right after the ajaxPage function. By right after I mean you do not wait for ajaxPage to return success. It is fired right after the ajax call goes out. It is very likely that it is not completed before your callback is fired.
As pointed out in the comments, this is due to the fact that AJAX calls happen asynchronously. The thread that
createReply
runs in continues to run before a response is returned from the server.You'll need to re-factor
ajaxPage
to accept a reference tocallback
, and call it when the response is ready. Something like:Then, in ajaxPage: