joe
joe

Reputation: 219

ajax data doesnt work in click event jquery

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?

Upvotes: 2

Views: 42

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29249

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);

Upvotes: 2

Related Questions