With the Web getting more and more advanced every day, it is impossible for any developer to not learn and adapt them. AJAX is one such thing. Ajax was first used by Google For Google Maps, Google Instant, etc. and since then it is something which is incorporated in any project, large or small.
So, What the Solution ?
jQuery standardize the process in all the browsers and eliminates the problem of browser compatibility. Also, the syntax is really clean and not complicated at all.
So, Here is how we create and Ajax Request using jQuery:
The two piece of code which we have written above is almost similar. Expect, One uses the GET method, while the Other uses the POST method.
So, let me explain the parameters we have given to both the functions. The First one which says ‘phpscript.php’, is the PHP script where we want out data to be sent for processing.
The second parameter is our data which we want to be processed. This data can be a form data, or anything else.
The last parameter, is the name of the callback function. If you do not want to create a separate callback function, you can use an anonymous function here as well, which is highly recommended. This function can also process any data returned from the PHP script as well. An If-Else Loop can be used to perform various actions.
Here is a Complete Example Of Code, of How We can use Ajax to perform a task on the page, without having to reload the page.
Throughout this post, I am assuming you have sufficient knowledge of PHP and SQL. So, In your PHP file you can the ‘action’ variable as ‘$_POST[‘action’]‘, and check if its value is true or not. After checking that, you can update your databases accordingly. You can use the Callback function, to make the update on the site.
Well, Once you get comfortable with Simple Ajax requests using jQuery. You will want to do complex actions as well. There are plenty of functions to make your life easier. One, such function is the serialize();. I will be writing an article about that function soon.
If You want to know, What the contents of the PHP file should be, and how to return Data from it, which will be processed by the callback function. Then Read this Article: How to Return Data From PHP File to AJAX Call (jQuery)