最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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(".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?

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?

Share Improve this question edited May 23, 2017 at 12:24 CommunityBot 11 silver badge asked Aug 11, 2011 at 21:07 Ricardo AltamiranoRicardo Altamirano 15.2k21 gold badges75 silver badges106 bronze badges 4
  • I had the same problem, was offered solutions. and ended up re factoring my code to meet my needs as this cannot be done nicely read here stackoverflow.com/questions/6877318/… – rlemon Commented Aug 11, 2011 at 21:12
  • what are you trying to do with the returned value, show more code – Johnny Craig Commented Aug 11, 2011 at 21:13
  • you could try posting the validation request then once you have the data call a function that will process it. Just also pass the parent element identifier with the data and you can run the validation function as a large switch->case – rlemon Commented Aug 11, 2011 at 21:15
  • When using asynchronous code, you're going to just have to let go of the hope of using the return value of your validate() function. It simply won't work. You need to accommodate your code to fit into the asynchronous flow. – user113716 Commented Aug 11, 2011 at 21:24
Add a comment  | 

4 Answers 4

Reset to default 7
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)

  1. 暂无评论