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. Commented Dec 4, 2012 at 20:29
  • Could it be because something is undefined? ;-) Commented Dec 4, 2012 at 20:47
  • Updated the question to make it more clear what I'm trying to do. Commented 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". Commented 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);
            }
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

try adding var before check

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

}

Comments

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

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.