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

Patricia Arquette
Release: 2024-10-28 03:27:02
Original
964 people have browsed it

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
}
Copy after login

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"},
  ...
});
Copy after login

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!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!