0

I have a function like this

function is_register(user_id){
    $.ajax({
        method: "POST",
        url: "functions.php",
        data: {user_id: user_id, action: "is_registred"}
    }).done(function(data) {
        return data;
    });
}

I want to execute this function somewhere else in my code, but it doesn't work :

is_register(user_infos.id, function(is_registred_status){   
    console.log(is_registred_status);
}

As you can see, I want the "is_register" function to be completly executed before continue, so I make a callback function to log the result. Where I'm wrong ?

William Ode
  • 188
  • 3
  • 11

3 Answers3

4

Just adding a function as a parameter doesn't make it a "callback" :)
You will have to call it inside of is_register at the "correct" place.

Another issue is the .done() part in your is_register function. In the passed callback function you're returning the value received by the $.ajax() call. But this is useless as the value will not be accessible (How to return the response of an asynchronous call)

In this case I would instead return the return value of $.ajax() (jqXHR object) and move the .done() part outside of the is_register function.

function is_register(user_id){
    return $.ajax({
        method: "POST",
        url: "functions.php",
        data: {user_id: user_id, action: "is_registred"}
    })
}

is_register(user_infos.id)
    .done(function(is_registred_status){   
        console.log(is_registred_status);
    };
Community
  • 1
  • 1
Andreas
  • 21,535
  • 7
  • 47
  • 56
  • hey buddy, you need to add some description along with your code, its a bad quality code. didn't expect this from someone of your reputation. – dreamweiver Oct 12 '15 at 10:40
1
function is_register(user_id , callback)
{
    $.ajax({
        method: "POST",
        url: "functions.php",
        data: {user_id: user_id, action: "is_registred"}
    }).done(function(data) {
        if(callback)
            callback(data);
    });
}
Diptox
  • 1,809
  • 10
  • 19
0

You need to use jQuery.when(), It Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

jQuery Code:

function is_register(user_id){
  return $.ajax({
    method: "POST",
    url: "functions.php",
    data: {user_id: user_id, action: "is_registred"}
  }).done(function(data) {
     return data;
  });
}

$.when(is_register(user_infos.id)).done(function(){
    console.log(is_registred_status);
});

Note:If its just a single deferred object your targetting like tin this case, then you dont need to use $.when(), instead the .done()/.success() callback can be used for that purpose.

dreamweiver
  • 6,002
  • 2
  • 24
  • 39