Marcus Tan
Marcus Tan

Reputation: 417

.ajaxComplete not working

Hi i currently having a problem with firing .ajaxComplete function, whereby it should be working on a demo site. I'm refer to this function from here http://www.bitrepository.com/a-simple-ajax-username-availability-checker.html

Here are my code :

    <SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html 
*/

pic1 = new Image(16, 16); 
pic1.src = "loader.gif";

$(document).ready(function(){

$("#userID").change(function() { 

var usr = $("#userID").val();

if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({  
    type: "POST",  
    url: "check.php",  
    data: "userID="+ usr,  
    success: function(msg){  
   $("#status").ajaxComplete(function(event, request, settings){ 

    if(msg == "OK")
    { 

        $("#userID").removeClass('object_error'); // if necessary
        $("#userID").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    }  
    else  
    {  
        $("#userID").removeClass('object_ok'); // if necessary
        $("#userID").addClass("object_error");
        $(this).html(msg);
    }  

   });

 } 

  }); 

}
else
    {
    $("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
    $("#userID").removeClass('object_ok'); // if necessary
    $("#userID").addClass("object_error");
    }

});

});

//-->
</SCRIPT>

I had try to alert the msg , the check.php able to return back the msg value, but it stop on the .ajaxComplete() there where it does not trigger the function after the .ajaxComplete(). Please guide me through this. Thanks

Upvotes: 2

Views: 4513

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

From the document

As of jQuery 1.8, the .ajaxComplete() method should only be attached to document.

So

$(document).ajaxComplete(function(event, request, settings){
});

But in your code, there is no need to use ajaxComplete, the success callback will be called only when the ajax call is finished, so you can just check the value of msg directly in it.

        $.ajax({
            type: "POST",
            url: "check.php",
            data: "userID=" + usr,
            success: function (msg) {
                if (msg == "OK") {
                    $("#userID").removeClass('object_error'); // if necessary
                    $("#userID").addClass("object_ok");
                    $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
                } else {
                    $("#userID").removeClass('object_ok'); // if necessary
                    $("#userID").addClass("object_error");
                    $(this).html(msg);
                }
            }
        });

Upvotes: 5

Related Questions