lars
lars

Reputation: 23

No AJAX call with live()-binded click

Im trying to use AJAX inside a live()-function but it does not work. Any suggestions? The ajax call is working (see example 1) and the click is registred (see alertbox 1, example 2) but when calling it inside that live()-click, the AJAX call does not return any data

//Ajax function which gets called
function ajaxFunc(){
   $.get("test.php", function(data){
     alert(data);    //Says "hello nerd!" from PHP script
   });
}

//Example 1. Works fine.
$('#button').click(function(){
   ajaxFunc();  //Alerts "hello nerd!"
});

//Example 2. Does not work
$('.category_item').live('click', function(){    
    alert("Testing. Yes, click works)";       //Alertbox 1, 
    ajaxFunc(); //Alerts a empty alertbox       Alertbox 2
});

Upvotes: 2

Views: 284

Answers (2)

Shurdoof
Shurdoof

Reputation: 1719

You have a syntax error:

alert("Testing. Yes, click works)";

should be:

alert("Testing. Yes, click works");

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074949

There's no reason that the quoted code wouldn't work if, as you say, you're seeing the "Testing. Yes, click works" alert. Note that your quoted code has a syntax error there, you have the " and ) reversed; I assume that was an artifact of posting the question, because you said it did work.

If you fix that, it works fine: http://jsbin.com/uvuyi4

And that makes sense; nothing in ajaxFunc relies on anything from the context in which it's called, so it doesn't matter where it's called from.

Upvotes: 1

Related Questions