What is the best way to handle ajax requests in php?

What is the best way to process ajax requests in php, given that there are a lot of such requests for every taste? For each request to have a php-file-handler on the server? Or in requests to transfer type of request and then in one fat php-dispatcher to smoke this type? How it’s done? I’m sure many people have dealt with this issue. Surely there are “best practices” and / or design patterns. Comrades php-shniki, share experience.
Do not offer PHP frameworks. I want to pick it with my hands.

Thank you


Answer 1, authority 100%

In my opinion, there are not many options here. Well, create a class that will process requests. One way or another, but you accept a parameter (either GET or POST) and, depending on the key, perform one or another action. In addition, it is not always necessary to create the same type of responses on request.


Answer 2, authority 100%

You should have a controller that prepares the data, and then the appropriate view is simply superimposed depending on the format in which the data is needed.

Pseudo-code example:

$data = <получаем данные для шаблона>    
if (isAjax){
    $response = getAjax($data)
}else {
    $response =getHtml($data);
}
echo  $response;//отдаем браузеру или как оно у вас организовано

Leave a reply

Please enter your comment!
Please enter your name here