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!