0

As part of a form’s validation process, I’m trying to check if the value entered into one of my text boxes already exists within the database.

My submit function calls a second validation function that uses an ajax call to return the matching number of lines within the DB. If the number of lines equals 0, I want to return a value of true. If the number of lines equals 1+, I want to return a value of false.

As the ajax call runs asynchronous, I only ever get true returned as the function completes before the ajax call is complete.

Reading the web I understand I need to use callbacks but can work out what to do/how to restructure my code.

Submit button function

(function() {
  $('#NewBookSave').on('click', function(e) {
    e.preventDefault();
    var newNameValidationResult = newNameValidation();
    alert("Validation = " + newNameValidationResult);

    // if validation = true submit form data.....
  });
}());

Validation Function

function newNameValidation() {
  var newNameValue = $("#NewName").val();
  var nameCount;
  var isFormValid = true;

  $.ajax({
    type: "POST",
    url: "data_process.php",
    data: {
      dataDisplayType: 3,
      newNameValue: newNameValue
    },
    success: function(data) {
      nameCount = data;
    },
    complete: function() {
      if (nameCount >= 1) {
        showErrorMessage(newNameValue, "Error message");
        isFormValid = false;
      }
    }
  });
  return isFormValid;
};
JV Lobo
  • 5,526
  • 8
  • 34
  • 55
Bob0.1
  • 19
  • 5
  • 2
    the code will have to wait for newNameValidation() function to be completed. To do that you can return a Promise in newNameValidation function and wait for the promise in the part of the code that calls to that function. – JV Lobo Feb 23 '19 at 11:31

3 Answers3

0

Use async false to run as synchronious.

$.ajax({
    async: false,// other parameters as normal
})
Nasir Kamal
  • 114
  • 1
  • 7
0

You can start with something like this. it's a simple callback function, but you may wanna use the success function directly without the complete. I can refactor the code for you if you can't figure it out.

(function() {
      $('#NewBookSave').on('click', function(e) {
        e.preventDefault();
        newNameValidation(function(valid){
            console.log(valid); 
        });

    // if validation = true submit form data.....
  });
}());

function newNameValidation(callback) {
  var newNameValue = $("#NewName").val();
  var nameCount;

  $.ajax({
    type: "POST",
    url: "data_process.php",
    data: {
      dataDisplayType: 3,
      newNameValue: newNameValue
    },
    success: function(data) {
      nameCount = data;
    },
    complete: function() {
      if(nameCount >= 1) callback(false);
      else callback(true);
    }
  });
};
// This is an edit
function newNameValidation(callback) {
  var newNameValue = $("#NewName").val();   
  $.ajax({
    type: "POST",
    url: "data_process.php",
    data: {
      dataDisplayType: 3,
      newNameValue: newNameValue
    },
    success: function(data) {
      if(data >= 1) callback(false);
      else callback(true);
    }
  });
};

Another option is to consider using promises instead of callbacks.

  • 1
    Thanks mehdi, flowing your example i have got the call back to work but do i get the call back to continue and run the remaining code in my main function. Eg Check any other validation rules i may have and save? – Bob0.1 Feb 25 '19 at 20:00
  • Yes, you can do that, actually, you can drop the validation from the success method, and pass directly the data to the callback. then do all the validation within, I think this might be cleaner. – Mehdi Benmesssaoud Feb 25 '19 at 22:56
  • great thank you and cleaner – Bob0.1 Feb 26 '19 at 07:51
0

You should read about success and complete. You have two events after ajax: success or error. If success, the code in success will execute, if error the code in error. But in any case, the code in complete will execute. Since you depend on your call to succeed, I would put the code in success alltogether.

Just submit the form in the result, note the else statement in success:

function newNameValidation() {
    var newNameValue = $("#NewName").val();
    var nameCount;
    var isFormValid = true;

    $.ajax({
        type: "POST",
        url: "data_process.php",
        data: {
            dataDisplayType: 3,
            newNameValue: newNameValue
        },
        success: function(data) {
            nameCount = data;
            if (nameCount >= 1) {
                showErrorMessage(newNameValue, "Error message");
            } else {
                $("#targetForm").submit();
            }
        },
        error: function() {
            // handle what went wrong with the call and alert the user?
        }
        complete: function() {
            // maybe some cleanup or postprocessing?
        },
    });
};
Daidon
  • 581
  • 1
  • 3
  • 14