RHPT
RHPT

Reputation: 2650

Calling a function inside a jquery click event

I am trying to call a function inside a click event with jQuery, but jQuery returns undefined when the function is called. What is the correct way to do this?

$(document).ready(function() {
   $('#my_button').click(function() {
      var valid = check(something);
      if (valid) { // do something }
   });

   check = function(param) {
     .ajax {
         // ajax params
         success: function(data) { 
            if (data)
               return true;
         }
     }
   }
});

if you do a console.log(valid), it is returned as undefined

UPDATE: I've added the code inside check(), which is an ajax call. That seems to be the problem. If I just do an alert() inside check, then everything works. So what's wrong with the ajax call?

Upvotes: 1

Views: 8618

Answers (4)

Brian Cray
Brian Cray

Reputation: 1275

The problem is check is an asynchronous event. You need to use a callback instead of a return statement:

$(document).ready(function() {
   $('#my_button').click(function() {
      check(something, function (valid) {
         if (valid) { // do something }
      });
   });

   check = function(param, callback) {
     $.ajax({
        // ajax params
        success: function(data) { 
            if (data){
               return callback(true);
            }
            else {
               return callback(false);
            }
        }
    });
});

Upvotes: 3

thatidiotguy
thatidiotguy

Reputation: 8991

I think you want this:

function check(param)
{
    //do something
    return true;
}

Then you can call check from wherever in your Javascript code.

Let me add that I thought this way was best since I do not like using function pointers unless there is a reason. There does not appear to be one in this case.

Upvotes: 2

Travis J
Travis J

Reputation: 82287

That is because check needs to be declared above the jquery click event I believe. Try this:

var check = function(param) {
 // do something
 return true;
}

$('#my_button').click(function() {
  var valid = check(something);
  if (valid) { // do something }
});

Upvotes: 0

lante
lante

Reputation: 7336

try adding var before check

var check = function(param) {
 // do something
 return true;

}

Upvotes: 0

Related Questions