I have a VERY bizarre (to me anyway)javascript issue. I was developing a page, and in the process of doing so, I threw in a couple of alert lines of code to help me debug. then, I got everything working. woo hoo, right? not so fast. as soon as I take out the alert (no other changes to the code) my code fails. the variable comes back as undefined. there is no logical reason I can come up with that would cause this. anyone have any ideas? here's the relevant code... the following WORKS, but of course the alert pops up :
function videoDone() {
$.ajax({url:"getNextTrack.php",success:function(result){
foo = result;
}});
alert(foo);
document.getElementById("myVideo").src = foo;
the code above works fine. it loads the next track thru jquery ajax, and sets the video source to that. happy days. HOWEVER, if I do nothing else but remove the alert and change the code to :
function videoDone() {
$.ajax({url:"getNextTrack.php",success:function(result){
foo = result;
}});
document.getElementById("myVideo").src = foo;
then foo comes back undefined. this just doesn't make sense to me. nothing else has been changed
In the script the code makes an Ajax call, which is an asynchronous call, meaning your code continues to execute while the call is made. In the code the document.getElementById...
line is dependent on data returned by the Ajax call. When the alert is not in place the document.getElementBy..
statement is called before the ajax call completes.
When in place, the alert is pausing the call long enough for the ajax call to complete. When you remove the alert, the call to grab the element and set the src attribute executes prior to the Ajax call returning. This causes foo to be undefined.
Simply include the code to set the src
attribute inside the callback function which is executed after the ajax call has completed.
function videoDone() {
$.ajax({url:"getNextTrack.php",success:function(result){
document.getElementById("myVideo").src = result;
}});
In a nutshell here is what happens:
Without Alert
- Ajax call fires
- document.getElementById... executes, throwing error
- Ajax call returns
With Alert
- Ajax call fires
- Alert window displays, pausing code execution
- Ajax call returns populating needed variables
- document.getElementById... executes, no error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With