Title: Ajax function in form submit
Last modified: August 30, 2016

---

# Ajax function in form submit

 *  Resolved [dgcov](https://wordpress.org/support/users/dgcov/)
 * (@dgcov)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/)
 * I’m checking my form against the user database to prevent duplicate emails before
   the form is submitted.
 * `<form id="registration" enctype="multipart/form-data" method="post" action=""
   onsubmit="return (validate_form());">`
 *     ```
       function validate_form(){
         var emailExists='';
         jQuery(document).ready( function($) {
             data={'action': 'checkemail_exists','umail': document.getElementById('email').value};
             jQuery.post( ajax_url, data, function(response) {
               emailExists=response;
             });
           });
         //... lots of other checks ...
         if(emailExists=='true'){
           warning=document.getElementById('email_r');
           warning.innerHTML='This email is already taken';
           warning.style.display='inline';
           warning.scrollIntoView();
           return false;
         }
         return true;
       }
       ```
   
 * The problem is that the **validate_form** returns true every time, regardless
   of whether the email is already registered or not.
 * if I add an **alert(‘wait for a moment’)** before the **if(emailExists==’true’)**
   statement, then it works ok.
 * So clearly I need to pause the routine for long enough to allow the ajax call
   to complete.
 * What would be the approved way of doing this?

Viewing 6 replies - 1 through 6 (of 6 total)

 *  [Igor Benic](https://wordpress.org/support/users/ibenic/)
 * (@ibenic)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522294)
 * The problem here is that you are doing the validation check outside the AJAX 
   call.
 * You should do the whole validation thing inside the AJAX response function.
 * The reason it works fine when you add an alert before that validation is because
   the AJAX thing will need a second or two to complete and while the user clicks
   on the alert message, the ajax is complete and the variable emailExists will 
   be filled with a new value.
 * But when there is no alert there is no “wait time” and so the script will complete
   even though the AJAX is still in progress. To fix that you need to put the whole
   validation of the Email inside the response function of the AJAX requrest.
 * Optional: You could make that inside a separate javascript function such as validateEmail()
   and then call that function inside the response function of the AJAX request.
 *  Thread Starter [dgcov](https://wordpress.org/support/users/dgcov/)
 * (@dgcov)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522312)
 * Ok, thanks: I’ll try that.
 * I had tried this:
 *     ```
       for(var i=0;i<60;i++){
           if(emailExists=='true'){
             warning=document.getElementById('email_r');
             warning.innerHTML='This email is already taken';
             warning.style.display='inline';
             warning.scrollIntoView();
             return false;
           }else if(emailExists=='false'){
             return true;
           }
           sleep(1000);
         }
       ```
   
 *     ```
       function sleep(delay) {
         var start = new Date().getTime();
         while (new Date().getTime() < start + delay);
       }
       ```
   
 * Firefox will timoout with a dialog box asking you to terminate the script or 
   continue. If you “Continue”, then the Ajax call completes. In other words, the
   same behaviour as the “alert(‘somestuff’)”.
 * However, this isn’t consistent amongst other browsers.
 *  [catacaustic](https://wordpress.org/support/users/catacaustic/)
 * (@catacaustic)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522318)
 * That’s not what Igor meant. 🙂
 * You have to do the checks inside the response function that happens after the
   result is returned. Like this..
 *     ```
       function validate_form(){
         var emailExists='';
         jQuery(document).ready( function($) {
               data={'action': 'checkemail_exists','umail': document.getElementById('email').value};
               jQuery.post( ajax_url, data, function(response) {
                     emailExists=response;
   
                     // Your checks go in this area.
   
                     if(emailExists=='true'){
                         warning=document.getElementById('email_r');
                         warning.innerHTML='This email is already taken';
                         warning.style.display='inline';
                         warning.scrollIntoView();
                         return false;
                     }
               });
           });
   
         return true;
       }
       ```
   
 * Again, your issue is that you have to wait until after the result comes back 
   before you can check anything, and the best way to do this is to do this inside
   the response function as you know that you will have a response.
 *  Thread Starter [dgcov](https://wordpress.org/support/users/dgcov/)
 * (@dgcov)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522358)
 * Yes, I posted that as a possible solution before I tried your suggestion of placing
   the validation code inside the Ajax function.
 * Placing the validation code inside the Ajax function works fine in Firefox, but
   not in Chrome where the submit button does not return so the user is left wondering
   why there is no response to him clicking the submit button.
 * I’ve (sort of) resolved this by adding an “onblur” event to the email field which
   calls the ajax function which sets a global variable if the email already exists
   and checking this variable in the validation code.
 * While this seems to work, I’m not convinced it is the recommended best practice,
   so I won’t mark this thread as “RESOLVED” just yet.
 *  [catacaustic](https://wordpress.org/support/users/catacaustic/)
 * (@catacaustic)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522363)
 * The JavaScript is your examples isn’t the best, and doesn’t quite do things the
   way that it should. It will work, but… 🙂 For a start, the call to `jQuery(document).
   ready()` should be a wrapper for everything.
 * I’d suggest something like this. You’d need to substitute your own ID’s for the
   submit button and the form, but this is more likely the way that it should be
   structured. This will also let you remove the `onclick=""` attribute from your
   form as that is all taken care of by the click action on your submit button.
 *     ```
       jQuery (document).ready (function () {
   
           jQuery ('#submit_button_id').click (validate_form);
   
       });
   
       function validate_form (e) {
           e.preventDefault ();
   
           var data = {
               'action': 'checkemail_exists',
               'umail': jQuery ('#email').val ()
           };
   
           jQuery.post (ajax_url, data, function (response) {
               if (response == 'true') {
                   warning = jQuery ('#email_r');
                   warning.html ('This email is already taken');
   
                   warning.style.display = 'inline';
                   warning.scrollIntoView ();
               }
               else {
                   jQuery ('#registration').submit ();
               }
           });
       }
       ```
   
 *  Thread Starter [dgcov](https://wordpress.org/support/users/dgcov/)
 * (@dgcov)
 * [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522403)
 * Thanks!
 * When I get a moment, I’ll study that.
 * I’m afraid that the JQuery stuff is a little esoteric for me and I tend to stick
   to plain Javascript where I can.
 * :+)

Viewing 6 replies - 1 through 6 (of 6 total)

The topic ‘Ajax function in form submit’ is closed to new replies.

 * In: [Hacks](https://wordpress.org/support/forum/plugins-and-hacks/hacks/)
 * 6 replies
 * 3 participants
 * Last reply from: [dgcov](https://wordpress.org/support/users/dgcov/)
 * Last activity: [10 years, 9 months ago](https://wordpress.org/support/topic/ajax-function-in-form-submit/#post-6522403)
 * Status: resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
