Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable value not set correctly

The variable value is not correctly set inside getJSON function. The variable $videoId displays 396 and 397 as expected in the first Alert.

But in the second alert, the value 397 is displayed twice.

Am I missing anything here? I could not find any other post here discussing this kind of issue. If so please point me over there.

Below is the jQuery code.

 $( "div .ow_video_list_item").each(function(){         
     $videoId = $(this).children("a").attr("href").split("/")[5];
     alert($videoId);    ==> First Alert

     $.getJSON("video/get-embed/" + $videoId + "/", function (data)   
     {                        
         $.each(data, function (key, code) {                                  
             alert($videoId);   ==> Second Alert
         });       
     });  

  });

Below is the HTML code:

<div class="ow_video_list_item ow_small">
    <a href="http://site.com/video/396">Video 1</a>
</div>

<div class="ow_video_list_item ow_small">
    <a href="http://site.com/video/397">Video 2</a>
</div>
like image 314
Purus Avatar asked Jan 30 '26 00:01

Purus


2 Answers

The other comments about the asynchronous nature of getJson are right. But mostly, the problem is that you use a global variable $videoId. If you replace:

$videoId = $(this).children("a").attr("href").split("/")[5];

by

var $videoId = $(this).children("a").attr("href").split("/")[5];

You will be fine, even when using async methods.

like image 72
Greg Avatar answered Feb 01 '26 16:02

Greg


Assuming $videoLink is in fact $videoId as pointed out by comments :

It is because the getJSON method is asynchronous and you are dealing with javascript closures. When you execute the getJSON callback :

function (data)   
     {                        
         $.each(data, function (key, code) {                                  
             alert($videoId);   ==> Second Alert
         }); 

you have looped on your first each loop and the $videoId have taken the last value hence the display of 397 two times.

Have a look at how javascript closures work here : How do JavaScript closures work?

like image 30
benzonico Avatar answered Feb 01 '26 16:02

benzonico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!