AJAX Request Callback with jQuery
In this article, we'll discuss how to handle AJAX callbacks using jQuery, specifically focusing on specifying the exact data to be returned.
Background
AJAX (Asynchronous JavaScript And XML) allows for asynchronous data exchange with a server, making it ideal for updating web pages without reloading the entire page. The .done() method is commonly used for processing data returned from an AJAX request.
Specifying Returned Data
Suppose you have a PHP script, convertNum.php, that doubles the value of a number received via an AJAX request. The challenge is to return only the doubled number, excluding other HTML markup.
Using a Separate PHP Script
One elegant solution is to create a separate PHP script, say returnNumber.php, that exclusively outputs the doubled number. This keeps the code organized and the PHP processing separate from the AJAX request.
Revised Code
Here is the revised code:
convertNum.php
<?php $num = $_POST['json']; if (isset($num)) { // Send AJAX request to returnNumber.php $ch = curl_init('returnNumber.php'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $num); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $doubledNum = curl_exec($ch); curl_close($ch); // Output the doubled number to the AJAX request echo $doubledNum; }
returnNumber.php
<?php if (isset($_POST['json'])) { $num = $_POST['json']['number']; if (isset($num)) echo $num * 2; }
AJAX Request
$.post("convertNum.php", {"json": json}).done(function (data) { // Process and use the returned doubled number here $('#numReturn').val(data); });
Advantages of this Approach
Conclusion
By utilizing a separate PHP script for data processing and AJAX callback, you can effectively specify the exact data you wish to receive. This method promotes code clarity and flexibility for future Ajax request handling.
The above is the detailed content of How Can I Specify the Exact Data Returned in a jQuery AJAX Callback?. For more information, please follow other related articles on the PHP Chinese website!