JavaScript | Ajax and PHP - perform operations in the background

What is Ajax? We often hear about it, but somehow can not see it? It's true, because Ajax operates asynchronously, performed in the background. For the user, it has no meaning, the only difference is the lack reload the page.

Ok. But why should I use Ajax? I will describe it by example. I'm building a website and user has ability to block his entries, but we would have to enter the editing of the entry and there to block entry. For this it is necessary to switch to separate page and then return to the previous page. Everything can be reduced to a single click. For example, click on the checkbox and in the background is saving to the database record new values​​. Ajax can be used to validate forms, loading new content, manage content on the site, interact with the user.

Ajax is a function of jQuery. Full description of the functions available in the documentation at The basic syntax I present below.

$.ajax({    type: "POST",    url: "ajax_page.php",    dataType: "json"    data: {wartosc1: "", wartosc2: ""},}).done(function(json) {});

Should be set type of which is to call, usually it will be a POST (for forms). We provide necessarily url for which data are sent. Url is a php file or function in the controller (for MVC). We set the data type, and set the values ​​for the variables that will be sent. Then, as we meet all the requirements, is called the file / function and perform in a manner invisible to the user. At the end turn result to Ajax. In the "done", we can check the status and outcome. We will, therefore, whether there are any errors and get variables with php. Sending variables between Ajax and PHP, and vice versa is possible thanks to JSON.

All nicely arranged, but what if you want to check some intermediate value during Ajax? Tab "Network (Network)" in your browser is good for this quest. Each browser provides the functionality for checking Ajax calls. We then preview the variables transmitted, url addresses, type of call, results and status.

The use of Ajax forces developers to prepare separate function responsible for handling and transferring data through JSON result. However, after writing several functions based on Ajax will find that it is not as difficult as it seemed at first.

An extension for Ajax can be AngularJS, which is around framework for JavaScript, but more about this will be in another article.