2

I want an alert to show up, after the second click. first in the li then in the div.button.

HTML

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

this function has an inner ajax call to retrieve the number of posts. Once I successfully has returned the data with ajax, and click the button, the alert doesnt show up.

JQUERY

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

   $(".button").on('click', function(e) {
       alert(total_posts);
     }
   });
}

It looks like the click event from buttom doesn't recognize the varia ble retrieved by ajax...what am doing wrong?

7
  • declare total_posts outside the ajax. until the ajax will not succeed, the total_post will be undefined. Commented Mar 13, 2018 at 12:27
  • if I define total_posts before the ajax call, for example var total_post=2000 when clicking the div.button it shows up an alert saying 2000 not the number retrieved by the ajax call. Commented Mar 13, 2018 at 12:32
  • Remove the var before total_posts in the success callback. Commented Mar 13, 2018 at 12:35
  • 1
    @MoshFeu I removed it. It work well now, thank you. Commented Mar 13, 2018 at 12:38
  • 1
    Answered, thanks :) and good luck! Commented Mar 13, 2018 at 12:56

1 Answer 1

2

When you declare a variable using var insides a function, its scope is only the function so it's not accessible outside of it.

So, you need to declare it outside the success function and set it in this function. Only then you will get the right value.

For example, this is not working becuase a's declaring is inside b function:

function b() {
  var a = 8;
}

b();
console.log(a);

This is also, will not work (the value of a will not change outside the b function scope)

var a = 8;
function b() {
  var a = 9;
  console.log('a inside b()', a);
}

b();
console.log('a outside b()', a);

So, you need to declare it at start and override it in the success callback.

var a = 8;
function b() {
  a = 9;
  console.log('a inside b()', a);
}

b();
console.log('a outside b()', a);

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

Comments

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.