0

In my PHP project I'd like to use AJAX technology. I am familiar with simply AJAX requests and simply responses, in which only simply answer such as "1" (user exists od "2" (user doesn't exist) is provided. In these cases there is no problem to process this type of response with using of jQuery, for instance.

But in some cases, I suppose more complex responses, which force re-render huge part of the page. I have following ideas, how to do it:

  1. Usings JSON data as the response of server-side script and process them with using of jQuery on client?

  2. Render full HTML code on the server, send it to the client as the response to the AJAX request and simply process it in "success" part of the ajax call?

What's the best approach for preparing the response on the server for complex request? I would like to use option 2) but I would like to avoid the following syntax:

$result = '';
$result = '<div>';
$result = '  <p>Username ' . $username . ' is not unique';
$result = '</div>';

return $result;

Is there a possibility to use something like "templates" for rendering ajax response? I would like to use pure PHP, no additional frameworks.

Radek Budař
  • 91
  • 1
  • 7
  • You could read a file with `file_get_contents()` and `eval()` it. Or you could define your own placeholders for variables an replace them with `preg_replace()`. – pixelarbeit Jan 27 '17 at 14:17
  • 1
    Method 1 is reasonable, as is method 2. It really depends on your use case. I'd prefer to return smaller amounts of data in something like JSON and update the page client side, as it probably means smaller and quicker AJAX requests than sending back lots of HTML which is probably already on the page. And yes there are templating methods that can generate HTML easier than chaining it all together. Google "PHP templating" to discover more... But this is a primarily "opinion based" question, IMO. – samiles Jan 27 '17 at 14:18
  • Thanks, but "replace" method is not enough, because I'd like to process some arrays etc in the template. I have no idea how to manage it with using of replace. – Radek Budař Jan 27 '17 at 14:20

1 Answers1

0

You can use the HTML template tag for this. It allows you to store HTML that can be used over and over.

In JavaScript, grab the template by it's ID, duplicate it (being sure to make a deep copy), then insert the required JSON values into the new template. You can then insert this into your page.

Alternatively, use a client side library such as handlebars.js.

Do not send HTML over PHP. It's just plain wrong.

  • According to this answer, I tried to implement it on my project. Server side script returns JSON data, on client side I use jQuery for processing them and append the result into the template. I think, it is the best approach in my case. The only one probelm is, that work with – Radek Budař Feb 02 '17 at 09:20