Home >Backend Development >PHP Tutorial >How Do I Retrieve and Display PHP Response Data Using AJAX?
Retrieve PHP Response via AJAX
In your AJAX request, you're attempting to retrieve an echo'd response from a PHP file (process.php). Understanding how to capture and utilize this response can be crucial.
To begin, let's examine the code snippet you provided:
<code class="javascript">$.ajax({ type: "POST", url: "process.php", data: somedata; success: function(){ //echo what the server sent back... } });</code>
In the success function, you need to capture the data returned by process.php. This data can be written directly to an element's innerHTML property. Here's an updated version of the code:
<code class="javascript">$.ajax({ type: "POST", url: "process.php", data: somedata; success: function(data){ $('#result').html(data); } });</code>
Now, in process.php, you can echo a simple string response, such as:
<code class="php"><?php echo 'apple'; ?></code>
Regarding your question about JSON, plain text will suffice in this scenario. JSON is primarily used when preparing data for asynchronous requests, such as in the case of RESTful APIs.
Lastly, to name the POST request, you can use the data parameter:
<code class="javascript">var formData = new FormData(); formData.append('name', 'John Doe'); $.ajax({ type: "POST", url: "process.php", data: formData; success: function(data){ $('#result').html(data); } });</code>
In this example, 'name' is the name of the POST request.
The above is the detailed content of How Do I Retrieve and Display PHP Response Data Using AJAX?. For more information, please follow other related articles on the PHP Chinese website!