1

wanted to check a value through ajax for validation purpose. my function getting respose true or false. but cannot return reponse to function callback_validation.

when i call below function its returning undefined.

console.log(callback_validation('value',<object>)); /* here its returning undefined */

Above function supposed to return me TRUE or FALSE.

find my action javascript function here:

        function callback_validation($val,$field){
        var $jObj=[],$data={
            ci: $ci,
            ui: $ui
        };
        $data[$field.attr('name')]=$val;
        $jObj.push($data);
        console.log(JSON.stringify($jObj)); /* CONSOLE OUTPUT: [{"ci":"","ui":"4934","refno":"s"}] */
        $.ajax({
            url: $url,
            type: 'post',
            dataType: 'json',
            success: function (res) {           
                /* console.log(res.valid); */ /* here its returning true / false */
                return res.valid;
            },
            data: $data,
            error: function(xhr, desc, err) {
                console.log(xhr);
                console.log('Details: ' + desc + '\nError:' + err + '\n');
                return false;
            },
            cache: false
        });
    }
Syed Nizamudeen
  • 440
  • 3
  • 7
  • 25
  • ajax is doing asynchronous call. You can't return the value as above. One option is to make the call sync add option as `async: "false",` OR with async call try to pass a callback function to your `callback_validation` which will get invoked on ajax response – vijayP Jan 06 '17 at 10:19

1 Answers1

2

AJAX is asynchronous meaning that you cannot return a value from the callback_validation that depends on the result of the AJAX call. The reason for that is because the success callback (which is the only place where you know the value) could be executed much after the function has already returned.

So I would recommend you start using the async pattern and have your function take a callback instead of returning a value:

function callback_validation($val, $field, resultCallback) {
    var $jObj=[], $data={
        ci: $ci,
        ui: $ui
    };
    $data[$field.attr('name')]=$val;
    $jObj.push($data);

    $.ajax({
        url: $url,
        type: 'post',
        dataType: 'json',
        success: function (res) {           
            resultCallback(res.valid);
        },
        data: $data,
        error: function(xhr, desc, err) {
            console.log(xhr);
            console.log('Details: ' + desc + '\nError:' + err + '\n');
            resultCallback(false);
        },
        cache: false
    });
}

and now you can call your function like that:

callback_validation('value',<object>, function(result) {
    console.log(result); // this will print true or false
});

It's just the asynchronous pattern of programming that you should get accustomed too if you are doing AJAX calls.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • you solution works fine! but it would be easy if i could call function like this `return callback_validation('value',);` . also i'm getting this error `Uncaught TypeError: Cannot read property 'message' of undefined` – Syed Nizamudeen Jan 06 '17 at 10:38
  • 1
    @SyedNizamudeen you might think it would be easier, but it's not because it's **asynchronous**. – freedomn-m Jan 06 '17 at 10:38
  • @freedomn-m can help me on this? – Syed Nizamudeen Jan 06 '17 at 10:58
  • It's not a matter of what is easier, but what is technically possible. As I mentioned if you are doing AJAX programming you'd better get accustomed to the asynchronous patterns of coding - which is use callbacks and not return values from functions. The sooner you get accustomed to this style, the better. – Darin Dimitrov Jan 06 '17 at 10:59
  • @SyedNizamudeen yes, read *and understand* the link for the possible duplicate. As Darin states, it's a paradigm-shift in your coding toolset. – freedomn-m Jan 06 '17 at 11:30