开发者

jquery - return value from callback function (in post request) into the function its inside of?

I have a javascript function that posts data to a validation script and grabs a value from there. The callback function on the post request returns a boolean value, and I'm trying to get the entire function to return that boolean value. Right now, the callback function returns the correct value, but the function itself doesn't return anything. Here's the code:

function validate(request_type, request_text) {
    $.post("http://www.example.com/ajax/validate.php",{
        type: request_type, 
        text: request_text
    }, function(data) {
        return (data == "valid");
    });
}

I realise that this is sort of a "synchronous" call, and that's not what AJAX is about, but I already have numerous functions in validate.php (database calls, etc.) that I can't implement in Javascript, and I saw threads like this one that talk about using some form of handler.

How would I write a simple handler that will make either the variable data or the result of the boolean comparison data == "valid" available when I use it in an if/else statement (which is where this function is supposed to be used)?

EDIT: For example, one of the if statements that will be using the boolean result:

if (!validate('password',pass_new)) {
        $('#pass_new').addClass('error');
        $('#pass_confirm_new').addClass('error');
        $(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
        $('#pass_text_short').hide();开发者_运维百科
        $('#pass_text_long').show();

EDIT: The function called with the onsubmit event in my HTML form:

function valid_pass_sett() {
    //code to remove errors left over from previous submissions - snipped
    pass_old = $('input[name=pass_old]').val();
    pass_new = $('input[name=pass_new]').val();
    pass_confirm_new = $('input[name=pass_confirm_new]').val();
    //some if statements that don't involve AJAX requests - snipped
    if (!validate('password',pass_new)) {
        $('#pass_new').addClass('error');
        $('#pass_confirm_new').addClass('error');
        $(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
        $('#pass_text_short').hide();
        $('#pass_text_long').show();
        return false;
    }

    return true;
}

I haven't edited this code to include the updated code that's been posted, but my question is how I return false from it to stop form submission?


function validate(request_type, request_text, callback) {
    $.post("http://www.example.com/ajax/validate.php",{
        type: request_type, 
        text: request_text
    }, function(data) {
        callback(data == "valid");
    });
}

And usage would be:

validate(request_type, request_text, function (isValid) {
    if(isValid) { 
        // do something
    } else {
        // do something if invalid
    }
});


Unless you make a synchronous AJAX call (which you probably don't want to do), you simply can't.

If this function is used in several places in your code, your best bet may be to allow it to receive a function.

That way instead of relying on the result being returned from your function to be used in some code, you're actually passing your code directly in, so it is ensured to be able to use the response.

var my_form = $('#my_form');

my_form.submit( valid_pass_sett );

function valid_pass_sett() {
    //code to remove errors left over from previous submissions - snipped
    pass_old = $('input[name=pass_old]').val();
    pass_new = $('input[name=pass_new]').val();
    pass_confirm_new = $('input[name=pass_confirm_new]').val();

    validate('password', pass_new, pswd_validation_callback); // async validation

    return false;  // cancel form submission
}

function validate(request_type, request_text, callback ) {
    $.post("http://www.example.com/ajax/validate.php",{
        type: request_type, 
        text: request_text
    }, callback );
}

function pswd_validation_callback( data ) {
    if ( data === 'valid' ) {
         // if valid, call the native .submit() instead of the jQuery one
        my_form[ 0 ].submit();
    } else {
         // Otherwise do your thing for invalid passwords.
         // The form has already been canceled, so no concerns there.
        $('#pass_new').addClass('error');
        $('#pass_confirm_new').addClass('error');
        $(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
        $('#pass_text_short').hide();
        $('#pass_text_long').show();
    }
}

EDIT: Changed to use code posted in question.

EDIT: Updating to work with additional code posted. Narrowing answer down to the named function for clarity.


function validate(request_type, request_text) {
$.post("http://www.example.com/ajax/validate.php",{
    type: request_type, 
    text: request_text
}, function(data) {
    return (data == "valid");
}); }

You can't really return from 'validate' the result of the AJAX call. You could try declare a variable before the $.post call, let's call it 'x', and inside the response function assign the value to that variable (x=data=="valid"), and outside the $.post block, but inside the 'validate' function, return that value.

function validate(request_type, request_text) {
var x;
$.post("http://www.example.com/ajax/validate.php",{
    type: request_type, 
    text: request_text
}, function(data) {
    x = data == "valid";
});
return x; }

The real problem is that the function 'validate' will continue even if the post call haven't return any value, so it will always be 'false'.

The best thing you can do is call another function INSIDE the response function, so you can assure that the server call is over before getting to the next part.

Edit:

It's been a long time since I posted this answer. The world has changed and so AJAX calls.

Now we have promises ;)

You still cannot return a direct value from a function, but you can return a Promise object, which can be chanined to another Promise, and the second promise will get the data you returned from the first one.

function validate(request_type, request_text) {

   var promise = $.ajax("http://www.example.com/ajax/validate.php",{
       type: request_type, 
      text: request_text
   });

function getStuff(data) {
    //Do something and return the data to the next promise
    return data;
}

promise.then(getStuff).then(function(data){
    // Do something else with data
});

}


If I understand this question correctly you can achieve what you want by simply storing the returned value into a HTML element and then return that elements value from your custom function:

    function validate(request_type, request_text){

       $.post("http://www.example.com/ajax/validate.php",{
          type: request_type, 
          text: request_text}, 
          function(data) {
             $('#someElement').text(data); 
          });

       //return the data by getting the value of the html element
       return $('#someElement').text();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜