0

I have this function to load data into #container, after clicking on the li.

HTML

<li onclick="$(document).ShowPosts(4)"></li>
<div class="more">[show posts]</div>

   <div id="container"></div>

JQUERY

jQuery.fn.ShowPosts = function(id_user) {

 var total_posts=999999999;

  $.ajax({
     type: 'POST',
     url: "total_posts.php",
     data: {
       'id_user': id_user
     },
     success: function(data) {
       var total_posts = data;
     });

    //load first group      
    $("#container").load(url_load,{id_user':id_user}, 
   function(){ alert(total_posts); /*shows up 9999999;*/
  });                


   $(".more").on('click', function(e) {
       alert(total_posts); /*shows up retrieved by ajax - correct;*/
     }
   });

}

PROBLEM

The problem is that after the first load .load(), within the load() function(){} the alert shows up total_posts as 9999999 (predefined value) when would have to be the retrieved by ajax total_posts.php

but in the .on() when clicking on .more the alert shows up correctly the value of total_posts.

Why does an alert shows up incorrect and correct values within the main function?

joe
  • 219
  • 2
  • 11
  • 1
    The A(Asynchronous) in AJAX means control does not wait for a response to before executing the statement(s) that follow. Therefore, `.load()` will execute before a response is received. – PeterKA Mar 14 '18 at 23:28
  • and why an alert shows up correct and the other one incorrect values? – joe Mar 14 '18 at 23:30
  • 1
    You have a global variable `total_posts` (which is not a good idea). By the time you click `.more` the ajax response has been received and the success callback has set that variable to the desired value. **If you happen to click before a response is received, you'll not get the desired value** – PeterKA Mar 14 '18 at 23:36
  • I understand... how do I fix this? – joe Mar 14 '18 at 23:40
  • See answer below. For more information see related question. – PeterKA Mar 14 '18 at 23:47
  • thank you. I have this last question...Is this the only way to fix this?....I thought something like `.on("load",...` delegate...or something like that...I dont know. – joe Mar 14 '18 at 23:52

1 Answers1

1

The following will ensure that you get the correct value by not executing .load() until an ajax response is received.

success: function(data) {
    var total_posts = data;
    //load first group      
     $("#container").load(url_load,{id_user:id_user}, function(){ 
         alert(total_posts); /*shows up 9999999;*/
     });
 });

NOTE: Do not unnecessarily clutter the global scope.

PeterKA
  • 24,158
  • 5
  • 26
  • 48
  • It solved my question. I have this other question, maybe you can help. https://stackoverflow.com/q/49287670/9485263 thank you. – joe Mar 14 '18 at 23:55