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>
Community
  • 1
  • 1
  • And where is this JSON coming from, ajax ? – adeneo Jul 15 '14 at 16:43
  • Because the alert is outside the function and gets called before the function is called. Put the alert inside the function. – Shaunak D Jul 15 '14 at 16:46
  • @ShaunakD - how would you know that, there's no function call at all in the posted code ? – adeneo Jul 15 '14 at 16:46
  • 1
    @adeneo Do you see one? `displayThumbnails` is not called. – Spencer Wieczorek Jul 15 '14 at 16:47
  • @adeneo, yes that is one scenario. If the function call is before the alert it should work. – Shaunak D Jul 15 '14 at 16:47
  • I've tested the above code with a function call between `alert(json);` and `var json='';` and the value of `json` was changed. – tcooc Jul 15 '14 at 16:48
  • 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 ? – adeneo Jul 15 '14 at 16:50
  • @ShaunakD Hello, I have made the function call from the mainpage.php which is the landing page of website. The DOM ready function makes the AJAX call, gets the data and this function is called and the response data is passed as parameter into this function. which is received in list here into this function as you can see above – user3841831 Jul 15 '14 at 17:31
  • Instead of describing what's called where, why not just paste the actual code? It will be a lot easier for us to follow what's going on than trying to interpret your last paragraph. – Patrick Q Jul 15 '14 at 18:43
  • This is a classical example of asynchronicity issues, you're calling the function from the ajax success handler, which is async, and had you posted the actual code right away this question would have been closed as a duplicate of [How to return the response from an Ajax call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call), which is what I expected, and why I asked the question in the very first comment. – adeneo Jul 15 '14 at 20:17

2 Answers2

5

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

Patrik Oldsberg
  • 1,540
  • 12
  • 14
  • 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. – user3841831 Jul 15 '14 at 17:27
  • Moreover should it not follow the proper top to bottom flow at run time like the other HTML and js files follow – user3841831 Jul 15 '14 at 17:32
  • It is only a function declaration, none of the code inside the function is executed until `displayThumbnails` is called from somewhere else. – Patrik Oldsberg Jul 15 '14 at 17:52
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

Kevin Sandow
  • 4,003
  • 1
  • 20
  • 33
  • 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. – user3841831 Jul 15 '14 at 18:14
  • 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: http://recurial.com/programming/understanding-callback-functions-in-javascript/ – Kevin Sandow Jul 15 '14 at 18:22