JavaScript's Ajax functionality only triggers when a fake line is added

Using the onblur event:

function ajaxFunction(obj) 
{
    var button = document.getElementById("submit");
    button.disabled = true;
    button.setAttribute("class", "test");
    var getdate = new Date();  
    xmlhttp.onreadystatechange  = handleServerResponse(obj);

    if(xmlhttp) 
    {
        xmlhttp.open("POST","register_ajax.php",true);
        xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xmlhttp.send(obj.name +"="+ obj.value);
    };
}

Revised handleServerResponse function:

function handleServerResponse(obj) 
{
    alert(xmlhttp.responseText);
    if (xmlhttp.readyState == 4)
    {
        if(xmlhttp.status == 200) 
        {
            obj.value=xmlhttp.responseText; 
        }
        else 
        {
            alert("Error during AJAX call. Please try again");
        }
    }
}

Answer №1

Your "efforts" seem to be successful at first, but in reality, they are not.

Here's what's going on:

  1. An xmlhttp request is sent (a response will come later).
  2. You immediately attempt to check the readyState, which is not yet 4 because it's still processing!

In another scenario:

  1. An xmlhttp request is sent (response coming later).
  2. You interrupt the process by triggering an alert. As you're dealing with the alert, the AJAX response arrives.
  3. You quickly check the readyState and now it is 4.

If you close the alert too fast, the issue will recur.

The correct approach for handling AJAX (and asynchronous processes in general) is to use event listeners.

xmlhttprequest.addEventListener("onreadystatechange", function (event) {
    if (xmlhttprequest.readyState === 4) {
        // handle response
    }
});

Answer №2

Here is an important line to note:

xmlhttp.onreadystatechange  = handleServerResponse(obj);

Instead of properly setting the on readystate change handler, you are mistakenly calling handleServerResponse. You should actually assign a function to xmlhttp.onreadystatechange rather than assigning the return value of handleServerResponse(obj). You should try this approach:

xmlhttp.onreadystatechange  = function(){
                                  handleServerResponse(obj);
                              };

Additionally, the reason why the second method worked is because the alert paused execution and allowed the ajax call to complete before the checks were performed.

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

What could be the reason why my AJAX error is not displaying the exception from my Webmethod?

I am currently utilizing Google Chrome for my work tasks. After referring to , I attempted to throw an exception from a webmethod. However, no output is shown in the console.log. The only information I received is a generic error message from the network ...

What could be causing the alteration of my JSON data when sent through a WEB.API Ajax request?

Before Ajax Call: "{ "UnitOfMeasureRelatedUnitDataInbound": [ { "Name": "test", "Active": true, "UnitOfMeasureTypeID": "dd89f0a0-59c3-49a1-a2ae-7e763da32065", "BaseUnitID": "4c835ebb-60f2-435f-a5f4-8dc311fbbca0", "BaseUnitName": null, ...

Steps to Execute a button press with Protractor

My task involves interacting with a popup that displays HTML code like this: <div class="ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"> <div class="ui-dialog-buttonset"> <button type="button">Ok</button> </d ...

Trouble with loading images on hbs/nodejs

I'm currently working on a web application using NodeJs and express-handlebars. However, I am facing an issue with images not displaying correctly on the HTML page that is being rendered using handlebars. Here is the structure of my app: The root fo ...

How can I use a specific condition to query for a particular element in an $in array in MongoDB?

Although I am skeptical that this is achievable, I will give it a shot here. Below are some examples of records in the database: { type: 'fruit', name: 'apple', quantity: 3 } { type: 'fruit', name: ' ...

Gathering screenshots of items hidden beyond pagination

Feel free to visit this site. My aim is to capture screenshots of all PDF links on a page when given a URL. To start, I tried requesting the URL and parsing the HTML text to find all PDF links: from bs4 import BeautifulSoup as soup import requests from ur ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

How to sort by a specific split part of an array using JavaScript and jQuery?

Looking to sort an array based on a specific split part of each element. example_array = ["Zebra:Add","Pay:Cold","And:Vets","Jam:Back"] The desired outcome is: console.log(code here) // prints ["Zebra:Add","Jam:Back","Pay:Cold","And:Vets"] Note: Each p ...

Troubleshooting unresponsive buttons within a $timout/ setTimeout function in Angular and Ionic

I am trying to implement a popup with a slight delay. However, I am encountering issues where the buttons are not functioning properly without the delay, and they do not appear when I add the delay. I have come across information online mentioning that $ti ...

Executing JavaScript code upon successful form submission: An overview

I need help with my Asp.Net MVC web application. I am trying to implement a feature where some code runs on the successful response of an API method called upon form submission. Here is the current code snippet: @using (Html.BeginForm("APIMethod", "Confi ...

"Encountered a type error: The .join method is not recognized as a function

Hello everyone, I've encountered an issue that has me a bit stumped. I recently took over a project and found a problem in which the previous developer was attempting to join an array of strings. Unfortunately, when I try to build the project, I keep ...

Obtain URL parameters prior to rendering with Next.js on the server side

Looking to retrieve the parameters from a URL coming from the Spotify API, for example: http//link.com/?code=examplecode. Is there a way to extract the value of "code" prior to rendering so that I can redirect it and transfer the code value to another p ...

How can I perform a subtraction operation with the 24-hour clock using JavaScript/JQuery?

I am trying to calculate the difference in hours between two time values. The values are provided in the format: 0530-2400 These values are stored as strings and I believe the first step is to convert them into JavaScript Date objects. Here is my current ...

Unable to establish SocketIO callback from client to server resulting in a null object instead

I'm encountering an unusual issue with SocketIO. On the server-side, I am using the emit() method like this: $s.sockets.emit(scope, {some: datas}, function(feedback) { console.log('received callback'); } ) ...

After logging in, AngularJS ensures that the window is brought into focus

My tech stack includes Angular, .NET, MVC, and VS2015. One issue I am facing on my website is with social login. After a user signs in, they get redirected from the main window to the login window. However, after a successful login, the user remains on th ...

Comparing WebSockets and XHR for transmitting data

Looking to optimize the architecture of a web application using Node.js, the goal is to efficiently send medium-sized files to the client from a gallery. Each gallery item should be delivered to the user as quickly as possible in binary form. The file size ...

The PHP application encountered an error when trying to use an object of the mysqli_result type as an array

In my section, I have a straightforward display of data sourced from the database. Upon clicking options like construction and selecting countries like Algeria, the displayed values are [251, 211,712]. Similarly, for selections like Power in Egypt, the ou ...

Using the after ship.com API with CORS in JavaScript using Ajax

Hi everyone, this is my first time posting here. I'm having trouble sending data via the POST method. When I checked the console, I saw the following error message: "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote ...

What is the best method in Django to dynamically load JavaScript based on the view name, if it exists?

In the realm of Django, I find myself faced with the challenge of loading a JavaScript file that matches the name of the view whenever I call said view with a template. For example, if I invoke the view foo, my goal is to automatically load foo.js from a ...

An innovative way to display or hide a div depending on the multiple selections made in a select2 jQuery field

A select2 jQuery dropdown menu is set up with two options: *For Rent *For Sales If the user selects 'For Rent', specific fields will be displayed below it, as well as for 'For Sales'. The challenge arises when both options are ...