Home  >  Article  >  Backend Development  >  How to Retrieve and Store a Response from a PHP File Using AJAX?

How to Retrieve and Store a Response from a PHP File Using AJAX?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 03:27:02965browse

How to Retrieve and Store a Response from a PHP File Using AJAX?

Obtaining Response from PHP File Using AJAX

In this scenario, you wish to acquire a response from process.php via AJAX. The objective is to capture this response and store it as a variable.

To initiate the process, the back-end PHP file (process.php) needs to echo the intended response, such as "apple" or "plum." Plain text suffices; encoding in JSON is not necessary.

The JavaScript code posted initially lacks a parameter in the success function of the AJAX call. To retrieve the server response effectively, add the following line:

success: function(data) {
   alert(data); // displays "apple" in the alert
}

The alert serves as an example; you can store the response in a variable by replacing this line with var response = data;.

As for naming the POST request, you can provide two arguments in the data parameter of the AJAX call:

$.ajax({
  ...
  data: {name: "someName", value: "someValue"},
  ...
});

This allows you to retrieve the named value from process.php using PHP's HTTP request accessors ($_POST['name'], $_POST['value']).

The above is the detailed content of How to Retrieve and Store a Response from a PHP File Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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