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.
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.
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.'
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.
Directly in the template:
{% if app.request.isXmlHttpRequest() %}
// code if ajax request
{% else %}
// code if not ajax request
{% endif %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With