Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Is it possible to get ajax params in json?

Started by Muut Archive 10 years ago · 3 replies · 630 views
10 years ago

I'm trying to implement "Display more pages" button using jQuery ajax and twig template.

My javascript looks like
$.ajax({
url: "/products.json.twig",
method: "GET",
data: { index: "0" }, //page index to show
success: function (data) {
....

Is it possible to read somehow data parameter in products.json.twig using twig? If not, how should I solve this problem? Thanks in advance!

10 years ago

You also have access to the Uri object in Twig so you should be able to do this:

TWIG
{% set var = uri.param('foo') %}
10 years ago

That AJAX request builds a request of type: /products?index=0, so you need to use uri.query('index') to get the value. uri.param() is to be used for grav parameters, which are more readable, e.g. site.com/products/index:0/, but the jQuery Ajax call does not builds urls in this style.

Take a look at the tests https://github.com/getgrav/grav/blob/develop/tests/unit/Grav/Common/UriTest.php for some pretty comprehensive examples of various URL structures.

Also, don't point your request to products.json.twig. Point it to products, if that is the URL that lists the products, and ask the server to return JSON, or use $.getJSON instead.

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1368 9 years ago
Archive · by Muut Archive, 9 years ago
2 940 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2960 9 years ago
Archive · by Muut Archive, 9 years ago
3 1125 9 years ago