Double request being sent by Ajax

Sample URL:

Note: Please use the test sign in credentials: test/test for username/password.

I am currently working on an AJAX request to fetch data from a database. The serverTime.php file appears to be functioning correctly as it is inserting and returning the expected responseText.

However, I have noticed that the request is being triggered twice. This was evident when debugging with Firebug. As a result, the page seems to 'reset' in some way, causing my cursor to lose focus from the current textbox. Additionally, even if my message is not empty, the URL shows "localhost/twitter/index.php?message=". I would like to resolve this minor issue before it escalates into a major problem.

Below is the JavaScript code. ajaxRequest represents my XMLHTTPRequest object. Any assistance would be greatly appreciated!

// Function to handle data received from the server
ajaxRequest.onreadystatechange = function(){
    if (ajaxRequest.readyState == 4){
        document.getElementById('output').innerHTML = ajaxRequest.responseText;
    }
}
// Build query string
var message = document.myForm.message.value;
var queryString = "message=" + message;

// Send AJAX request
ajaxRequest.open("GET", "serverTime.php" + "?" + queryString, true);

ajaxRequest.send(null);

Thank you,

Paragon

Answer №1

This situation is not unfamiliar to me, and in my experience, the culprit has often been firebug. To troubleshoot, I recommend disabling firebug and trying to submit the request again. You can use tools like Fiddler or other means to confirm that the request is only being executed once.

Answer №2

When I implement AJAX functions in JavaScript, a key strategy I use is maintaining a state variable to control the timing of requests. This prevents multiple requests from being sent simultaneously and ensures that each request is handled properly. To achieve this, follow these steps:

  1. Start by setting an inProgress variable to false.
  2. Prior to calling ajaxRequest.send(), switch inProgress to true. Ensure that you only call ajaxRequest.send() when inProgress is set to false.
  3. Within ajaxRequest.onreadystatechange(), reset inProgress back to false once the request reaches state 4.

However, there are scenarios where queuing actions becomes necessary. In such cases, simply ignoring requests while another one is in progress may not suffice. Here's my recommendation for handling queued actions:

  1. Begin by initializing an ajaxQueue as an empty global array.
  2. Before triggering ajaxRequest.send(), add the request to ajaxQueue.
  3. In the ajaxRequest.onreadystatechange() function, check if the request has reached state 4. If it has, remove the serviced request from the queue. Then, if ajaxQueue still contains pending requests (array size > 0), extract another request from the queue and invoke send() on that object.

Answer №3

After some troubleshooting, I discovered that the issue I was facing had nothing to do with AJAX. It turned out to be a minor and unusual problem related to how my form handled the Enter key in textboxes. Strangely enough, having two textboxes allowed me to submit without reloading the page, but with just one textbox, the page would refresh.

To improve reliability, I decided to update my event system by implementing jQuery to detect when the Enter key is pressed on specific textboxes.

I appreciate the valuable input from those who helped shed light on my initial misconception. Thank you for your assistance!

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

Can JavaScript be used to bypass AJAX cookies?

Is there a way in JavaScript to programmatically ignore server-sent cookies without adjusting browser settings? We have implemented plugins on our web server that periodically update our security cookie, resulting in compatibility issues with certain URLs ...

Received an unexpected GET request while attempting to modify an HTML attribute

After clicking a button in my HTML file, a function is called from a separate file. Here is the code for that function: function getRandomVideoLink(){ //AJAX request to /random-video console.log("ajax request"); var xhttp = new XMLHttpRequest( ...

How to locate an ID following an AJAX call in jQuery

I am experiencing an issue with a button that is supposed to print a form containing data based on different IDs, where each form has a unique ID. The problem arises when the main page fails to locate these IDs. Below is the JavaScript code responsible f ...

A guide to creating a TypeScript redux middleware class

As specified in the typescript definition for Redux, these interfaces must be implemented to create middleware: /* middleware */ export interface MiddlewareAPI<D extends Dispatch = Dispatch, S = any> { dispatch: D getState(): S } /** * A midd ...

What is the process of turning an SVG element into a clickable link?

Is there a way to transform each element within an SVG image embedded in an HTML file into an active link? I want to create an SVG image with clickable elements. Here is a snippet of the SVG image: <svg version="1.1" id="Layer_1" xmlns="http://www.w3 ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

Is there anybody who can assist me with ${}?

Having an issue with using ${'variable'+i} in a loop function. The goal is to call each function from a loop. Explored template literals but couldn't find a solution for this specific problem. Desired format: ${'variable'+i} // (w ...

Retrieve the class name based on the ID of the final appearance of the div using jQuery

<div class='user user1' id='newuser'></div> <div class='user user2' id='newuser'></div> <div class='user user3' id='newuser'></div> To retrieve the class name ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

When attempting to retrieve data in a server-side component, Next.js encountered an ECONNREFUSED error with ::1:3000

import React from "react"; import axios from "axios"; interface UsersType { id: string; firstName: string; lastName: string; email: string; } interface dataProps { allUsers: UsersType[]; } async function getData() { try { c ...

"Ensuring Data Integrity: SQL Server Update Command for Unique Columns with Pre-Update

Scenario: A situation arises where an admin user adds a new client to the database with three unique columns: Postgres ID, similar to a driver's license, and an email. Later on, when attempting to allow the admin user to update these fields, validatio ...

Encountering a 400 bad request error when attempting to utilize AJAX within a WordPress environment

I am encountering a 400 error while attempting to retrieve the response from WordPress AJAX. Despite multiple attempts, I have been unable to pinpoint the root cause of the issue. The jQuery version being used is 3.6 and the filter.js file appears to be fu ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

How to choose `optgroup` in Vue 1.x

In previous iterations of vue.js, developers had the ability to generate a dynamic select list utilizing optgroups similar to the example found here. In the latest versions of vue, the documentation suggests using v-for within the options instead of optgr ...

I am having issues with the external CSS and JS files not functioning properly in my project

I'm currently working on a project that has the following file structure: However, I am facing issues with loading my CSS and JS files... <link rel="stylesheet" href="./css/main.css"> <script src="./js/main.js" ...

Using Webdriver to dynamically enable or disable JavaScript popups in Firefox profiles

I am currently working on a test case that involves closing a JavaScript popup. The code functions correctly in a Windows environment, but when I try to deploy it on a CentOS based server, I encounter the following error: Element is not clickable at point ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

One single block preventing all asynchronous jQuery/ASP.NET AJAX calls

My JQuery application is set up to make four asynchronous calls to four different asp.net web services, each on its own timer. However, I noticed that when I introduced a Thread.Sleep(10000) command in one of the web services, it ended up causing delays i ...

Utilize Google Tag Manager to search and substitute characters within a variable

Within my GTM setup, I have a CSS selector variable in the DOM. This variable pertains to real estate and specifically represents the price of a listing. My goal is to eliminate the characters ($) and (,) from this variable as part of meeting the requireme ...