1

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?

4
  • Unable to reproduce jsfiddle.net/mowglisanu/ZQxRv, maybe you should show the commented out code.
    – Musa
    Dec 4, 2012 at 20:29
  • Could it be because something is undefined? ;-)
    – leon
    Dec 4, 2012 at 20:47
  • Updated the question to make it more clear what I'm trying to do.
    – RHPT
    Dec 5, 2012 at 0:28
  • @Musa it works when I'm just calling an alert inside the check function. However, if I run an ajax call, then it goes back to "undefined".
    – RHPT
    Dec 5, 2012 at 0:33

4 Answers 4

3

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);
            }
        }
    });
});
0
2

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.

0

try adding var before check

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

}

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.