Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My code stops working when I remove "alert()"

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

like image 682
user2559867 Avatar asked Dec 26 '22 00:12

user2559867


1 Answers

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

  1. Ajax call fires
  2. document.getElementById... executes, throwing error
  3. Ajax call returns

With Alert

  1. Ajax call fires
  2. Alert window displays, pausing code execution
  3. Ajax call returns populating needed variables
  4. document.getElementById... executes, no error
like image 154
Kevin Bowersox Avatar answered Jan 06 '23 01:01

Kevin Bowersox