1

I have come across thing which is bothering me. The code I made is as follows

var json='';
function displayThumbnails(list) {
    json = list;
    for(var i in list)
    {
        var image = $("<img class='item'>").attr("src", list[i].thumbnail);
        $("#showThumbnails").append(image);
    }  
}
alert(json);

I would like to ask that variable json has a scope outside function also but the alert shows blank value.

When console.log(json) is inside the function result is displayed. Scope of json does not end after the function yet alert shows blank value. Why.?

On Public Demand :D

This is mainpage.php

<script>
  $(document).ready(function() {
      var jqxhr = $.get( "php/list.php",  function() {
      })

      .done(function(data) {
        var list = JSON.parse(data);
        console.log(list);
        displayThumbnails(list);

      })

      .fail(function() {
        alert( "Oh Snap, Server Error.!!! Try Again" );
        location.reload();
      });
  });
</script>
10
  • And where is this JSON coming from, ajax ? Commented Jul 15, 2014 at 16:43
  • Because the alert is outside the function and gets called before the function is called. Put the alert inside the function. Commented Jul 15, 2014 at 16:46
  • @ShaunakD - how would you know that, there's no function call at all in the posted code ? Commented Jul 15, 2014 at 16:46
  • 1
    @adeneo Do you see one? displayThumbnails is not called. Commented Jul 15, 2014 at 16:47
  • 2
    @SpencerWieczorek - Nope, I wrote "there's no function call .." so obviously I didn't see a function call, but the OP writes "When console.log(json) is inside the function result is displayed", so it's called somewhere, but who knows where ? Commented Jul 15, 2014 at 16:50

2 Answers 2

5

When the alert(json) statement is reached the function displayThumbnails hasn't been called yet, so the value of json is still '';

Sign up to request clarification or add additional context in comments.

3 Comments

How to get a way round this. I also face such issues where AJAX call is made which runs Async and rest scripts having dependency on it end up having null or empty values. I read that this can be done by making call async: false which is a bad coding practice.
Moreover should it not follow the proper top to bottom flow at run time like the other HTML and js files follow
It is only a function declaration, none of the code inside the function is executed until displayThumbnails is called from somewhere else.
0

Your variable is both accesibly by the code inside the function declaration and after the declaration. The issue here, as mentioned in the other answer is, that the code for filling the variable hasn't been executed yet.

To make sure that your code using the variable is only executed after the variable has been filled you can use a callback function, similar to this:

var json=''; 
// the second parameter should be a function
function displayThumbnails(list, callback) {
  var i, image;
  json = list; 
  for(i in list) { 
    image = $("<img class='item'>").attr("src", list[i].thumbnail);
    $("#showThumbnails").append(image);
  } 
  callback();
} 

doSomethingWithYourVariable = function() {
  alert(json);
};

// you can pass a callback function either by name, 
// then your call then should look similar to this:
displayThumbnails(list, doSomethingWithYourVariable);

// or pass an anonymous callback function:
displayThumbnails(list, function() {
  alert(json);
});

You also should never declare a variable in a loop, it will cost performance.


Short explanation of callbacks:

You pass another function (aka callback) to into your first function call. After the first function completes it will/should at some point call your callback function. This way you can get control and by this I mean the possibilty to insert code into the execution.

In the example above using a callback isn't really useful since all calls made are synchronous calls; but callbacks provide real value in an asynchronous environment and since AJAX calls are always asynchronous they are mostly used there.

jQuery.get('list.php', function(data) {
  // this already is an asynchronous callback function
  // that will be called when the request completes
});

// code here would be called immediately
// the request will most likely not be completed and no data available

For a more detailed introduction see Understanding callback functions in Javascript

2 Comments

Hey @Kevin Busse, I have just started to code. I am unaware of callback(); Can I read this chain calls somewhere? This term is also used alot in AJAX. I want a document to explain why this is called as callback and how to use them apart from ajax.
You can use it to do call chaining, or to give back control to from where an asynchronous call has been made. Since every AJAX call is asynchronous it is used there a lot. I will update my answer accordingly. For a general introduction to callbacks see: recurial.com/programming/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.