PHP interaction with jQuery (and JavaScript)


Good afternoon! I started studying web programming relatively recently. During this time, I managed to learn quite well PHP, HTML, CSS, a little Javascript and just a little jQuery. In practical site programming, I encountered the need for dynamic things for the site that would work without reloading the page. As you know, this can not be achieved using PHP. Therefore, I turned my attention to JavaScript and jQuery.

Tell us a little about the interaction of PHP with jQuery and JavaScript. How the data is exchanged, if such a need arises. For example, there is an element "like"(heart) that marks the reader's liking for the article, he clicks it and the jQuery code is triggered-without updating the page, the value of the new "like" should be added, then this increased by one value should be added to the database, that is, by means of PHP to write to Mysql. How are such things implemented? Tell me...

I looked at this article PHP library for jQuery and a lot of things I didn't understand. In an accessible language, explain how to link the jQuery framework or even just pure JavaScript with PHP. I will be grateful for the answer.

Author: IntegralAL, 2013-10-29

1 answers

It's very simple. Using AJAX ($.ajax() in jQuery or XMLHttpRequest in pure JS) a request is sent to the server. At the same time, the page does not reload. From the server's point of view, the request is exactly the same as requests sent when clicking on links or entering an address in the address bar. Here is an example in jQuery:

On the client:

$.ajax(
    type: 'GET',                   // тип запроса
    url: 'test.php',               // отправляем запрос на страницу test.php
    data: { name: 'Ivan' })        // данные, которые будут переданы с запросом
    .done(function(data) {         // объявляем обработчик для принятых данных
        alert(data);
    })
    .fail(function() {             // объявляем обработчик для ошибок
        alert('error');
    }

On the server (test.php):

echo 'Hello, ' . $_GET['name']

When running an AJAX request, a background request will be sent test.php?name=Ivan, a response was received ('Hello, Ivan'), which will be passed to the done handler.

On pure JS, the code would look a bit more cumbersome:

var xhr = new XMLHttpRequest();
var params = 'name=Ivan'
xhr.open('GET', 'test.php?' + params, true);       // последний параметр - делать ли запрос асинхронным. Если запрос не асинхронный, он подвесит страницу до тех пор, пока не придёт ответ
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {                     // запрос завершён
        if (xhr.status == 200) {                   // код 200 - успешно
            alert(xhr.responseText);
        } else {
            alert('error');
        }
    }
};
xhr.send(null);                                    // в качестве параметра передаются данные, посылаемые на сервер. Для GET-запросов параметр равен null, для POST-запросов - данным, которые нужно передать на сервер.

Thus, you can get any data from the server. If the data is part of the HTML markup, it is passed in its pure form. If the data has the form of any objects, then they are passed to the client in the form of JSON. A PHP associative array with any degree of nesting can be easily converted to JSON by the json_encode function. On the client, you need to convert the received string to an object. This is done by the JSON.parse function().

 4
Author: fori1ton, 2013-10-29 11:57:28