If you have come looking for this post. I am Assuming you Have
Sufficient Knowledge of PHP and jQuery, and you very well know how to
use jQuery’s AJAX function.
In any case, if you do not know how to use jQuery’s AJAX function Please read this article first. How To Process an AJAX Request Using jQuery
Okay. So, Let us see How are we going to process the Data Returned by the PHP file, and use it in jQuery’s Callback function.
When, I saw the function(data), which is the 3rd parameter in the $.post() function, then I immediately wanted to know what that ‘data’ is. And I did find it out.
The ‘data’ is the text printed(echoed) by the .php file upon processing. Suppose, we used the following function to send an AJAX call.
Here is the process.php file:
In the Process.php file, make sure you do not have any unnecessary
white spaces before or after the opening and closing PHP tags.
Otherwise, it may lead to a problem, which will make you scratch your
head. Trust me, I did.
So, to Return anything from the PHP file, we can simple use the echo statement. As a Beginner, I thought, we would be using a return statement, which is wrong.
We can also make the PHP file, return a JSON Object. And then we can use jQuery’s inbuilt functions to parse a JSON object.
So, if you have any questions. You can just comment below. I will reply for sure.
In any case, if you do not know how to use jQuery’s AJAX function Please read this article first. How To Process an AJAX Request Using jQuery
Okay. So, Let us see How are we going to process the Data Returned by the PHP file, and use it in jQuery’s Callback function.
When, I saw the function(data), which is the 3rd parameter in the $.post() function, then I immediately wanted to know what that ‘data’ is. And I did find it out.
The ‘data’ is the text printed(echoed) by the .php file upon processing. Suppose, we used the following function to send an AJAX call.
1 2 3 4 5 6 |
$.post('process.php', 'action=true', function(data) {
if (data == 'success')
//do something here
else
//tell the user something went wrong
});
|
1 2 3 4 5 6 7 8 9 10 |
<?php
if ($_POST['action'] == true) {
//CODE TO UPDATE THE DATABASE.
//Use PDO or MySqli functions. Or you will be vulnerable to SQL Injection.
echo "success";
}
else {
echo "failure"
}
?>
|
So, to Return anything from the PHP file, we can simple use the echo statement. As a Beginner, I thought, we would be using a return statement, which is wrong.
We can also make the PHP file, return a JSON Object. And then we can use jQuery’s inbuilt functions to parse a JSON object.
So, if you have any questions. You can just comment below. I will reply for sure.