0

I have a function called getData which makes an ajax request. I want to use this ajax request result on my form submission for validation along with other validation. Since ajax is asynchronous i am calling a callback function inside my success function.

Now i want to assign the callback function value to a javascript variable for my form validation. I have tried using jquery validation submit handler method but that doesnt work either. My callback function is returning the desired output, but when i try to console.log the variable i have assigned it too, it returns undefined

Here is my code

function getData(cb){
    $.ajax({
             url:'/stops/reason_valid',
              method: 'get',
             dataType: "json",
             success: function(data)    {
               if(data.reason == '6'){
                   if(($('.search_of_item1').is(':checked')) || ($('.search_of_item2').is(':checked'))){
                      $(".searchValidError").hide();
                      cb(false);
                    }
                    else{
                         $(".searchValidError").show();
                         cb(true);
                    }
               }
            }
          })
  }

  $(".actionstaken_submit").click(function(e){

    var validationFailed = false;
    var searchValidation = getData(function(cb){
          alert(cb);
          return cb;
          });
    console.log(searchValidation);

    if($('.no_validation').is(":checked")){
      if($('.action_validation:checked').length > 1){
        $('.noneError').show();
        validationFailed = true;
      }
      else{
        $('.noneError').hide();
        validationFailed =  validationFailed || false;
      }
    }

    if (validationFailed || searchValidation) {
       e.preventDefault();
       return false;
    }
  });

Note: if i do alert(cb) display's the appropriate value but console.log(searchValidation) returns undefined

6
  • getData() doesn't return anything Commented Jun 20, 2019 at 17:09
  • you forgot to close the apostrophe in: url:'/stops/reason_valid, Commented Jun 20, 2019 at 17:11
  • I updated my question, the thing is my ajax works properly fine as in my alert i get the cb value as true or false based on the condition, i am just able to assign cb value to the searchvalidation variable, any idea of how can i do that? @Anatsu Commented Jun 20, 2019 at 17:22
  • I tried returning cb from my getdata function but that doesnt help either @Taplar Commented Jun 20, 2019 at 17:22
  • getData() invokes an ajax method. You are trying to treat asynchronous logic like synchronous logic. It's not going to work with returns Commented Jun 20, 2019 at 17:27

2 Answers 2

1

....Since ajax is asynchronous i am calling a callback function inside my success function.

Right. But there is an issue. You continue to fail when you write:

var searchValidation = getData(function(cb){
      alert(cb);
      return cb;
});
console.log(searchValidation);

This is like you are doing the same error: the function is asynchronous as the call. There is more than one approach to solve your issue. I suggest you to consider the jQuery event property isTrigger. When you rise an event with .trigger() the event object contains such a property.

Hence, you can change your code to:

$(".actionstaken_submit").click(function (e) {
            if (e.isTrigger !== undefined) { // <-- is event risen from .trigger() ?
                return;
            }
            e.preventDefault();

            var validationFailed = false;

            if ($('.no_validation').is(":checked")) {
                if ($('.action_validation:checked').length > 1) {
                    $('.noneError').show();
                    validationFailed = true;
                }
                else {
                    $('.noneError').hide();
                    validationFailed = validationFailed || false;
                }
            }

            getData(function (searchValidation) {
                console.log(searchValidation);
                if (!(validationFailed || searchValidation)) {
                    $(".actionstaken_submit").trigger('click'); // <-- raise the event
        }
    });
});

Another solution can be based on triggering the submit event:

$(".actionstaken_submit").closest('form').trigger('submit');

function getData(cb) {
    cb($(':checkbox').prop('checked'));
    return;
    // for debug purposes....
    $.ajax({
        url: '1.json',
        method: 'get',
        dataType: "json",
        success: function (data) {
            if (data.reason == '6') {
                if (($('.search_of_item1').is(':checked')) || ($('.search_of_item2').is(':checked'))) {
                    $(".searchValidError").hide();
                    cb(false);
                }
                else {
                    $(".searchValidError").show();
                    cb(true);
                }
            } else {
                cb(false); // <-------  added.....
            }
        }
    })
}
$(".actionstaken_submit").click(function (e) {
    if (e.isTrigger !== undefined) { // <-- is event risen from .trigger() ?
        return;
    }
    e.preventDefault();

    var validationFailed = false;

    if ($('.no_validation').is(":checked")) {
        if ($('.action_validation:checked').length > 1) {
            $('.noneError').show();
            validationFailed = true;
        }
        else {
            $('.noneError').hide();
            validationFailed = validationFailed || false;
        }
    }

    getData(function (searchValidation) {
        console.log(searchValidation);
        if (!(validationFailed || searchValidation)) {
            $(".actionstaken_submit").trigger('click'); // <-- raise the event
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form >
    <input type="checkbox"> searchValidation?<br/>
    <input type="submit" class="actionstaken_submit" value="Submit">
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

Hi I change the code on the fly but what you have to do is run the validations of your click event inside a callback, or a deferred method as done or then.

Example:

function getData(){
   return $.ajax({
             url:'/stops/reason_valid',
              method: 'get',
             dataType: "json"
          })
  }

      function validate_submit(e){

  var validationFailed = false;
        var searchValidation = false;
     getData(searchValidation,validationFailed)
     .done((data)=>{


         console.log(data);
        if(data.reason == '6'){
      if(($('.search_of_item1').is(':checked')) || ($('.search_of_item2').is(':checked'))){
        $(".searchValidError").hide();
      }
      else{
        $(".searchValidError").show();
       searchValidation = true;
      }
    }
     }).always(()=>{
         console.log(searchValidation);
         if($('.no_validation').is(":checked")){
      if($('.action_validation:checked').length > 1){
        $('.noneError').show();
        validationFailed = true;
      }
      else{
        $('.noneError').hide();
        validationFailed =  validationFailed || false;
      }
    }

    if (validationFailed || searchValidation) {
       e.preventDefault();
       alert('oh shit here we go again');
       return false;
    }
     })
return false;
}

  $(".actionstaken_submit").click(function(e){
       validate_submit(e);
  });

Hope it helps =)

3 Comments

This works but for some reason even after entering thisif (validationFailed || searchValidation) { e.preventDefault(); return false; } code it ends up submitting my form @stan Chacon
add return false outside of the ajax call thats the only way
Even the edited version always submitted the form @stan Chacon

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.