Priority of ajax execution in jquery

  • 2020-06-19 09:40:46
  • OfStack

During user registration today, I found a strange problem. Please see the code:


$('input[name="username"]').blur(function(){
    // Verify the format 
    var pattern = /^[a-z][\w]{4,11}$/i;
    if(!pattern.test($(this).val())) {
      $(this).siblings('.desc').html('<font style="color:red;">5-12 Characters must begin with a letter. Only Numbers, letters, and underscores can be entered </font>');
      return false;
    }
    // Verify that the user name is registered 
    $.post('register.php?act=checkUser',{username:$(this).val()},function(data){
      if(data.status == 'error') {
        $('input[name="username"]').siblings('.desc').html('<font style="color:red;">'+data.info+'</font>');
        return false;
      }
    },'json');
    
    // successful 
 alert(' successful ');
    //$(this).siblings('.desc').html('<img src="./public/images/ok.gif" />');
  });

In principle, the above format is

1. Verify whether the user name conforms to the format
2. AJAX determines whether the user name is occupied with the correct format.
3. Correct icon will be displayed if both are successful.

But the question is when I verify that the user format is successful, it goes straight to alert(' successful ') and then ajax. Why? Is it a matter of time for ajax to execute? Or something else??

Here is the PHP code:


if($_GET['act'] == 'checkUser') {
  if($_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest') exit(' Illegal operation!! ');

  $sql = "SELECT id FROM {$sys_vars['db_pre']}user WHERE username='{$_POST['username']}'";
  
  $result = mysql_query($sql);
  $data = mysql_fetch_assoc($result);
  if ($data) {
    exit(json_encode(array('status'=>'error','info'=>' The user name has been registered!! ')));
  }else{
    exit(json_encode(array('status'=>'success')));
  }
}

Analysis of the following

ajax is an asynchronous operation. When ajax functions are executed, the system returns the function first and then makes a request. When the result of the request is received, it will be returned to the user by calling the callback function.


$('input[name="username"]').blur(function(){
    // Verify the format 
    var pattern = /^[a-z][\w]{4,11}$/i;
    if(!pattern.test($(this).val())) {
      $(this).siblings('.desc').html('<font style="color:red;">5-12 Characters must begin with a letter. Only Numbers, letters, and underscores can be entered </font>');
      return false;
    }
    // Verify that the user name is registered 
    $.post('register.php?act=checkUser',{username:$(this).val()},function(data){
      if(data.status == 'error') {
        $('input[name="username"]').siblings('.desc').html('<font style="color:red;">'+data.info+'</font>');
        return false;
      }
    },
    function(data){  // for post Function, the first 3 The parameters are callback functions 
      alert(' successful ');
    }
    ,'json');
    
    // successful 
 //alert(' successful ');
    //$(this).siblings('.desc').html('<img src="./public/images/ok.gif" />');
  });

Revise 1 like this, try, experience 1 different.
Different ajax functions use callback functions in slightly different ways, please refer to the w3school tutorial or jQuery website.

This is really a synchronous and asynchronous problem with js, which you can imagine is the next two lines


-- Perform function calls -- The regular verification -- initiate ajax-- The function returns          ajax The callback
                            |                        |
                            |                        |
                           Browser request --php To deal with -- Browser receives results

If you want the function to return after the ajax callback, you can change the above model, for example:


-- Perform function calls -- The regular verification -- initiate ajax                  ajax The callback -- The function returns
                            |                        |
                            |                        |
                           Browser request --php To deal with -- Browser receives results

This can be done by modifying whether the jquery originating ajax is asynchronous or synchronous!


$('input[name="username"]').blur(function(){
  // Verify the format 
  var pattern = /^[a-z][\w]{4,11}$/i;
  if(!pattern.test($(this).val())) {
    $(this).siblings('.desc').html('<font style="color:red;">5-12 Characters must begin with a letter. Only Numbers, letters, and underscores can be entered </font>');
    return false;
  }
  // Verify that the user name is registered 
  var ajaxCheckUser = false;
  $.ajax({
    type: "POST",
    url: "register.php?act=checkUser",
    data: {username:$(this).val()},
    //  Note that there 
    async:false
    success: function(data){
    if(data.status == 'error') {
      $('input[name="username"]').siblings('.desc').html('<font style="color:red;">'+data.info+'</font>');
      //return false;
    } else {
      ajaxCheckUser = true;
    }
  },'json');
  
  if(ajaxCheckUser) {
    // successful 
    alert(' successful ');
    //$(this).siblings('.desc').html('<img src="./public/images/ok.gif" />');
  }
  
});

This is the end of this article, I hope you enjoy it.


Related articles: