search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
this is not a browser bug, but a misunderstanding of the asynchronous execution mechanism
use the event listener and then operate the DOM after the response is ready
Always bind event listeners before send()
Home Web Front-end JS Tutorial How to correctly use XMLHttpRequest to send an asynchronous POST request and handle the response

How to correctly use XMLHttpRequest to send an asynchronous POST request and handle the response

Mar 15, 2026 am 06:09 AM

How to correctly use XMLHttpRequest to send an asynchronous POST request and handle the response

This article explains in detail the root cause of "empty response" in XMLHttpRequest asynchronous requests - reading the responseText directly without waiting for the request to be completed, and provides the correct writing method based on event monitoring. It also compares and recommends a more modern and concise Fetch API implementation solution.

The problem you encountered is very typical: accessing xmlhttp.responseText immediately after xmlhttp.send(), but getting an empty string - this is not a browser bug, but a misunderstanding of the asynchronous execution mechanism . XMLHttpRequest runs asynchronously by default (the third parameter is true). Send() will return immediately after being called, but the server response may arrive after several milliseconds or even hundreds of milliseconds. At this time, responseText has not been assigned a value, so it is naturally empty when it is read forcefully.

And alert() "coincidentally" pauses the execution of the code, giving the network request enough time to complete. Therefore, it seems "effective", but in fact it is an unreliable race trap.

✅ The correct approach is: use the event listener and then operate the DOM after the response is ready . The key is to use the load event (equivalent to readystatechange and readyState === 4 && status === 200):

 function submit_cost_code() {
  const costCode = document.getElementById("cost-code").value;
  const xhr = new XMLHttpRequest();
  const url = 'process-cost-code.php';
  const params = 'cost-code=' encodeURIComponent(costCode); // ✅ Prevent special characters from destroying parameters xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  // ✅ Register the load event handler xhr.addEventListener('load', function() { before send
    if (xhr.status >= 200 && xhr.status  {
    document.getElementById("feedback").innerHTML = "Network request failed, please check the connection";
  });

  xhr.send(params);
}

? Notes:

  • Always bind event listeners before send() , otherwise the event may be missed;
  • Use encodeURIComponent() to encode parameter values ​​to avoid submission exceptions caused by spaces, &, =, etc.;
  • Check xhr.status to ensure that the HTTP status code is normal (such as 200), rather than relying solely on whether responseText is non-empty;
  • Add error event monitoring to cover network interruption, cross-domain rejection and other scenarios.

?More recommended: Use modern fetch() API (good compatibility, Chrome 42/Firefox 39/Edge 14):

 function submit_cost_code() {
  const costCode = document.getElementById("cost-code").value;
  const formData = new FormData();
  formData.append('cost-code', costCode);

  fetch('process-cost-code.php', {
    method: 'POST',
    body: formData // ✅ Automatically set Content-Type to multipart/form-data
    // If application/x-www-form-urlencoded is required, use:
    // body: new URLSearchParams(formData).toString()
  })
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.text();
  })
  .then(text => {
    document.getElementById("feedback").innerHTML = text;
  })
  .catch(err => {
    document.getElementById("feedback").innerHTML = 
      `Submission failed: ${err.message}`;
  });
}

? Summary: asynchronous ≠ "automatic wait". Whether using XMLHttpRequest or fetch, the data must be processed through callbacks (events/.then()) after the response is ready. Abandon alert() as a "delay technique" and embrace event-driven or Promise chains in order to write robust and maintainable front-end interaction logic.

The above is the detailed content of How to correctly use XMLHttpRequest to send an asynchronous POST request and handle the response. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Correct way to dynamically access form control values ​​in Angular Correct way to dynamically access form control values ​​in Angular Apr 16, 2026 am 08:42 AM

In Angular, if you need to dynamically obtain the value of a specified control in the FormGroup through function parameters, you should use square bracket syntax (controls[gotInput]) instead of dot syntax (controls.gotInput). Otherwise, an error will be reported because the property name is treated as a literal instead of a variable.

How to create scheduled events in Discord.js How to create scheduled events in Discord.js Apr 21, 2026 am 04:09 AM

This tutorial details how to create Discord scheduled events using the discord.js library. We'll address a common TypeError when initializing GuildScheduledEventManager, explaining that its root cause is that the constructor expects a Guild object rather than a guild ID string. By obtaining the correct Guild object and passing it to the manager, developers can successfully create and manage scheduled activities for the server.

How to encapsulate reusable Axios POST request function How to encapsulate reusable Axios POST request function Apr 28, 2026 am 04:38 AM

This article explains how to correctly encapsulate the axios.post request into a reusable function. The core is to explicitly return the Promise instance to avoid interruption of the call chain and Cannot read properties of undefined (reading 'then') errors due to omission of return.

How to display variable content correctly in textarea How to display variable content correctly in textarea Apr 22, 2026 am 04:42 AM

This article explains in detail how to dynamically insert PHP variable values ​​into HTML textarea elements, focusing on correcting the common errors of "nesting span tags within textarea" and "misusing jQuery .html() method to set text area content", and provides a safe and standard PHP output solution.

How to properly handle return values ​​from asynchronous AJAX requests How to properly handle return values ​​from asynchronous AJAX requests Apr 21, 2026 am 06:36 AM

The fundamental reason why return returns undefined in JavaScript is that XMLHttpRequest is an asynchronous operation. The function has been executed and returned before the response arrives. At this time, the variables assigned in the callback have not yet taken effect. You must ensure you get a true response via Promise/async-await or synchronous requests (not recommended).

How to preserve Unicode variable names (such as π) when packaging in esbuild How to preserve Unicode variable names (such as π) when packaging in esbuild Apr 17, 2026 am 04:17 AM

By default, esbuild escapes non-ASCII characters (such as the Greek letter π, Chinese identifiers, etc.) into Unicode encoding (such as \u03C0). You can disable escaping through the --charset=utf8 parameter so that the Unicode identifiers in the source code are output as they are. The premise is to ensure that the running environment correctly declares UTF-8 encoding.

How to correctly use Promise.all to load multiple image resources in parallel How to correctly use Promise.all to load multiple image resources in parallel Apr 23, 2026 am 04:00 AM

This article explains in detail why the array length returned by Promise.all is abnormal (only the last result is included), and provides a reusable image loading function implementation to ensure that each element returns a Boolean status independently, and finally obtains a complete and ordered loading result array.

marked.js custom image rendering: handling non-standard syntax and path prefixes marked.js custom image rendering: handling non-standard syntax and path prefixes Apr 22, 2026 pm 11:00 PM

This tutorial details how to customize image rendering behavior using the renderer option of marked.js. In response to the needs of non-standard Markdown image syntax (such as ![[filename.jpg]]) and image URL path prefixes, the article provides specific code examples and explanations to guide readers on how to achieve dynamic processing of image paths and precise generation of HTML tags by overriding the default renderer.image method to meet specific rendering requirements.

Related articles