Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How AJAX calls work with TWIG

I am trying to understand how Twig can load a template through AJAX. From their website, it is clear how to load a template (http://twig.sensiolabs.org/doc/api.html)

echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));

But how would this work for an AJAX call? How would you tell Twig that you want to 'render' something that is only a part of index.html ... and not reload the entire page? I looked at Twig's sole Ajax example (http://twig.sensiolabs.org/doc/recipes.html), but this doesn't explain how Twig knows what part of the page you want to change. Assuming your Ajax call results in page content updates. I just need a simple example of this, something more than what is on Twig's recipe page.

like image 428
user1082428 Avatar asked Jan 04 '13 09:01

user1082428


People also ask

Do AJAX calls pass cookies?

AJAX calls only send Cookies if the url you're calling is on the same domain as your calling script. This may be a Cross Domain Problem.

What is AJAX call with example?

The ajax() method can send all type of http requests. The following example sends http POST request to the server. Example: Send POST Request. $.ajax('/jquery/submitData', { type: 'POST', // http method data: { myData: 'This is my data.'

What is an AJAX API call?

AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here.


2 Answers

Directly in the template:

{% if app.request.isXmlHttpRequest() %}
  // code if ajax request
{% else %}
  // code if not ajax request
{% endif %}
like image 100
Mick Avatar answered Sep 30 '22 03:09

Mick


There are several ways to accomplish that :

1) Separate your index.html in several files like index.html and content.html. Then use include function in index.html to include content.html.

Example :

if(isAjaxRequest()) //try to find the right function here
   echo $twig->render('content.html', array('the' => 'variables', 'go' => 'here'))
else
   echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here'));

Edit : If you do your ajax request with jQuery for example :

$.get('yoururl', function(data) {
  $('#divtoremplace').html(data);
});

2) Use the request.ajax boolean in your index.html

{% if request.ajax == false %}
<p>My header,  not reloaded with ajax</p>
{% endif %}

<p>My content, reloaded with ajax</p>

{% if request.ajax == false %}
<p>Other content,  not reloaded with ajax</p>
{% endif %}

Not sure about the second one, but this should do the trick accordind to the documentation. The best way is the first solution, separate your code.

like image 41
Pierrickouw Avatar answered Sep 30 '22 04:09

Pierrickouw