Issue with AJAX Complete event not functioning

Currently, I am facing an issue with firing the .ajaxComplete function on a demo site. I have referred to this function from this link.

Below is 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 attempted to alert the msg and found that the check.php is able to return the value of msg. However, it seems to stop at the .ajaxComplete() function and does not trigger the function after that. Any guidance on how to resolve this would be greatly appreciated. Thank you.

Answer №1

Referencing the official document

In jQuery version 1.8 and later, it is recommended to only use the .ajaxComplete() method when attached to the document.

Therefore,

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

If you take a look at your code, there is no necessity for using ajaxComplete. The success callback function will automatically be triggered once the Ajax call is completed, allowing you to directly access the value of msg within it.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The JavaScript program is occasionally receiving unconventional input

I'm really struggling with this one. As part of a programming exercise, I am developing a JavaScript calculator. You can access the functioning calculator here on Codepen. At the bottom left corner of the calculator interface, you will notice a "+-" ...

Angular's Routeprovider: Navigating Your Way through the

I am a newcomer to Angular and I encountered an issue while trying to implement routeProvider in my app. The error message that keeps appearing is: Uncaught Error: [$injector:modulerr] Failed to create module 'app' due to: Error: [$injector: ...

Can you provide the function that updates subscription and account details using Recurly JS?

Recurly has unfortunately declined to provide assistance with this issue. I must understand the specific format of the objects, as Recurly will not process any extra data or incorrect query arguments (which vary for each function). Ruby: subscription = ...

Tips for extracting data from a JQuery table with Python

My goal is to extract information from the top ten items on a manga website using Python Selenium/BeautifulSoup. However, I am facing challenges due to the website loading its content through a jquery script. The tutorials and guides I have followed do not ...

How can I combine multiple textures from mtlLoader and objLoader in three.js?

I have the files .mtl, .obj, and several .jpg textures. I have been attempting to use different textures in the export loader OBJ, and while I can see my object on the scene, it appears as a black color. Can anyone spot what might be incorrect or missing ...

The code for populating the lookup does not perform as expected on the initial attempt

I've encountered an issue with my JavaScript code on a form where it auto populates 2 lookup fields with the current user when the record is being created. Most of the time, this function works as intended. However, I've noticed that during the f ...

Container slide-show fill error

I'm attempting to create a slide show with an overlapping caption that appears when hovering over the container or image. The image needs to fit exactly inside the container so no scroll bar is shown and the border radius is correct. I managed to achi ...

Node.js - CSRF Protection Token Undefined

I've been facing challenges with setting up CSRF token generation, and I seem to be missing something. server.js: // configuration ====================================================================== var express = require('express'); va ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

What is the best way to implement validation for a textfield to prevent submission if a negative value is entered?

I am working with a text field of type number and I have successfully set a minimum value of 0 to ensure that negative values are not accepted. However, I have encountered an issue where I am unable to delete the 0 once it is entered. Is there a way to fix ...

Enhance the functionality of various textareas by implementing bullets for easier organization and formatting

Is there a way to add bullets to hidden textareas that are created dynamically? Currently, I can add bullets to visible textareas but would like the functionality to extend to newly created ones as well. Additionally, is it possible for these new bullets t ...

Javascript - Incrementing value upon key press, but limited to occurring only once

I am currently working on a script where I need to increment a variable by 5 each time the up key is pressed. The issue I am facing is that the variable keeps increasing continuously from a single keypress, whereas I want it to increase in steps of 5 (e.g. ...

Extract data from a CSV table stored in a variable using node.js

Currently, I am working on a node application that can potentially result in a CSV formatted table being stored in a variable. I am interested in converting this CSV data into a JSON format. I have explored various modules, but it appears that most of th ...

Error occurred during JSON transmission to REST API - Access-Control-Allow-Origin restriction encountered

I am looking to send JSON data to my REST API. I have successfully tested it using Postman, but now I want to send data from my frontend. However, I am unsure about where to add the header and how to do it. My backend is built with Spring Boot and my front ...

Stop duplicate submissions made through ajax requests

I am currently using AJAX to generate a list of replies. At the end of the reply list, I have included a textarea form that allows users to add their own reply (also using AJAX). However, I am encountering an issue where I call my JavaScript in my main P ...

Currently I am developing a Minimax Algorithm implementation for my reversi game using react.js, however I am encountering a RangeError

I've been implementing a Minimax Algorithm for my reversi game to create a strong AI opponent for players. However, I ran into the following error message: "RangeError: Maximum call stack size exceeded" How can I go about resolving this issue? Here ...

Retrieve elements within the array ranging from index 1 to 5 using Javascript

How can I log items from index 1 to 5 in the current array by using a loop? let cars = ["AUDI","BMW","LEXUS","VOLKSWAGEN","FERRARY","PORSCHE"] for (let i = 0; i < cars.length; i++) { if (i >= 1 && i <= 5) { console.log("The current ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

Utilizing jQuery for resizing images

I'm encountering an issue with my Jquery code as I work on creating a gallery feature. My goal is to have the selected image appear in the center of the screen when clicked, resized to fit the screen size if necessary. However, I've run into perf ...