How to Retrieve Server Response in AJAX Requests
You're utilizing AJAX to submit data to a PHP file named "process.php." However, you'd like to capture the server's response, such as "apple" or "plum," and store it in a variable.
Here's a breakdown of the necessary steps:
On the PHP Side:
Modify your "process.php" file to echo the desired response:
<code class="php"><?php echo 'apple'; ?></code>
On the JavaScript Side:
In your AJAX request, include the following line to define the success handler:
<code class="javascript">success: function(response) { // Store the server's response in a variable var result = response; // Perform actions based on the response if (result == 'apple') { // Do something specific for apples } else if (result == 'plum') { // Do something specific for plums } }</code>
Regarding JSON:
You don't necessarily need to echo the response in JSON format. Plain text will suffice in this case.
Assigning Name to POST Request:
To specify a name for your POST request, add the following line before sending the request:
<code class="javascript">$.ajax({ ..., data: { somedata: 'data content' } ... });</code>
This will assign the name "somedata" to the POST request.
The above is the detailed content of How to Capture Server Response in AJAX Requests and Handle it in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!