0

I have one form field that requires unique code value. When user tries to enter new record or update existing record I have to check if this code already exist in Database. I came up with solution where I use on blur function to send Ajax call and then return true or false. If returns false that means that value already exist and user will be notified, if true they can save the record. Here is example of my function:

$('.check-code').on('blur',checkCode);
function checkCode(e) {
    e.preventDefault();
    var element = $(this).get(0), // Dom element
        fldVal = $(this).val(), // Field value
        isValid; // Flag variable.

    if(!fldVal){
        isValid = false
        return;
    }

    $.ajax({
        type: 'POST',
        url: 'AjaxFunctions.cfc?method=checkCode',
        data: {'fldVal':fldVal},
        dataType: 'json'
    }).done(function(obj){
        if(obj.STATUS === 200){
            if(obj.RESULT === true){
                isValid = true;
                element.setCustomValidity("");
            }else{
                isValid = false;
                element.setCustomValidity(obj.MESSAGE);
            }
        }else{
            $('#frm_message').show().addClass(obj.CLASS).html(obj.MESSAGE).delay(7000).fadeOut('slow').queue(function(){
                $(this).removeClass(obj.CLASS).dequeue();
            });
        }
    }).fail(function(jqXHR, textStatus, errorThrown){
        alert('Error: '+errorThrown);
    });
}

//This function submits the form
$('.frm-Submit').on('submit', submitFrm);
function submitFrm(e){
    e.preventDefault(); // Prevnts default form submit.

    var frmID = formData = $(this).serialize();

        $.ajax({
            type: 'POST',
            url: 'AjaxFunctions.cfc?method=saveFrm',
            data: formData,
            dataType: 'json'
        }).done(function(obj){
            if(obj.STATUS === 200){
                //Success.
            }else{
                //Failed.
            }  
        }).fail(function(jqXHR, textStatus, errorThrown){
            alert('Error: '+errorThrown);
        });
}

One problem that I found was if I click to edit existing record and I change the code. Then I click on Submit button and my on blur function is not triggered. So in this case user will submit duplicate code because on blur did not run before submit. I'm wondering if there is a way to prevent this behavior?

espresso_coffee
  • 5,610
  • 10
  • 65
  • 159
  • 1
    From your code, on blur is working - https://codepen.io/nagasai/pen/GBNoJE?editors=1010 and one way to avoid submitting duplicate is to disable submit , till get response from ajax and enable if it is not duplicate – Naga Sai A Jul 19 '18 at 15:18
  • A better way is to listen on input and use of a timeout after each input disable submit then search your database and enable submit – Darkrum Jul 19 '18 at 15:19
  • The blur event triggers, but the form will also submit and not wait for the ajax call to come back *asynchronously* with its response. – trincot Jul 19 '18 at 15:20
  • @Darkrum I'm not sure that I understand your feedback. Can you provide small example? My code on blur function works fine the problem is if I click on the fields with `check-code` class and right after that click on submit button. In that case my on blur function never gets triggered. – espresso_coffee Jul 19 '18 at 15:21
  • @trincot What would be the best way to prevent that before on blur is completed? – espresso_coffee Jul 19 '18 at 15:21
  • @espresso_coffee your blur does fire though. – Darkrum Jul 19 '18 at 15:22
  • You should not use a standard submit button (or else cancel its effect), and only submit explicitly (with the `submit` method) in your code when the time is right. – trincot Jul 19 '18 at 15:22
  • @trincot Can you provide some example it will be easier to understand your solution? – espresso_coffee Jul 19 '18 at 15:24
  • Just research with the elements I gave you. See https://stackoverflow.com/questions/3314989/can-i-make-a-button-not-submit-a-form and https://stackoverflow.com/questions/16415740/jquery-resume-form-submit-after-ajax-call – trincot Jul 19 '18 at 15:26
  • @trincot If I do that and use button instead of submit I won't be able to use HTML5 validation. I'm not sure this is a good fit in my case. Also I'm not sure how that will change anything. I want to prevent submit before input field with the value is checked. Thank you. – espresso_coffee Jul 19 '18 at 15:27
  • You misunderstand. You need to programmatically submit the form when you have the ajax response. And choose one of the possible ways to not submit immediately when user clicks the submit button. – trincot Jul 19 '18 at 15:34
  • @trincot I can basically then `disable submit` button until ajax returns object in the first function where value is being checked. Then if value is ok enable submit button. – espresso_coffee Jul 19 '18 at 15:35
  • 1
    @espresso_coffee, same thing, i have mentioned in my first comment – Naga Sai A Jul 19 '18 at 15:38
  • @NagaSaiA Yes, correct. The only thing I need is maybe to fore HTML5 validation message to show if ajax returns false. Do you know the way to achieve that? – espresso_coffee Jul 19 '18 at 15:40
  • try something like this after getting false - $(".check-code").setCustomValidity("code already exists, try new code"); – Naga Sai A Jul 19 '18 at 15:44
  • @NagaSaiA I do have that part already set but message won't show until I click on submit button. I would like that to show automatically on ajax success if value is false. Does that make sense? – espresso_coffee Jul 19 '18 at 15:45
  • one option is to use .show() and .hide() based on the value , instead of relying on submit for validations for this scenario – Naga Sai A Jul 19 '18 at 15:53
  • @NagaSaiA So fat I think that best solution is on `focus` `blur`. When field is in focus then I disabled submit button, on blur I run the function and send ajax call. – espresso_coffee Jul 19 '18 at 17:22

0 Answers0