tags:

views:

56

answers:

2

I have this code below. I randomly ran across that it will work if I have that alert message exactly where it is. If I take it out or move it to any other spot the tabs will not appear.

What exactly is that alert doing that allows the code to work and how can I make it work without the alert?

$.ajax({
   type: "GET",
   url: "../ajax.php",
   data: "action=tabs",
   dataType: "json",
   success: function(Projects){
     $.each(Projects, function(i){

        /* Sequentially creating the tabs and assigning a color from the array: */
        var tmp = $('<li><a href="#" class="tab green">'+Projects[i].name+'<span class="left" /><span class="right" /></a></li>');

        /* Setting the page data for each hyperlink: */
        tmp.find('a').data('page','../ajax.php?action=lists&projectID='+Projects[i].project_id);

        /* Adding the tab to the UL container: */
        $('ul.tabContainer').append(tmp);

    });
   }
 });
    alert("yes");

The ajax code is retuning json with this code

        $query = mysql_query("SELECT * FROM `projects` ORDER BY `position` ASC");

    $projects = array();

    // Filling the $projects array with new project objects:

    while($row = mysql_fetch_assoc($query)){
        $projects[] = $row;
    }

    echo json_encode($projects);

The returning data is very small and very fast so I don't think that is the problem.

+1  A: 

AJAX is asynchrone! so the success handler of the ajax request gets executed AFTER the rest of your code gets executed. By adding the alert() you block your code long enough that the success handler gets executed. Simply move the code into the handler you are done.

ZeissS
+2  A: 

This is because Ajax requests are Asynchronous. They run alongside the main script, and are not necessarily completed when you do your $.each(Projects, function(i).

Showing and clicking away the alert() gives the script enough time to fetch the data, which is why it seems to work that way.

You need to put the full procedure into the success callback:

 success: function(data){
       Projects = data; 
       $.each(Projects, function(i){
         ........... // do all the stuff

   }
Pekka
Correct answer. As a side note, he can make the AJAX call synchronous by setting async: false ... but it comes with a performance hit.
Gert G
too simple. Can't believe I didn't think of that. Thanks!
James