Reputation: 117
I am working on Symfony2 project. And now want to add some dynamic actions. I want to use jQuery and Ajax calls and API.
Below I wrote my project model.
Issue is there where I put "?" on the picture.
For example I have comments in my page and 2 buttons "oldest" "newest".
Basically on the page load TWIG load comment to my view and everything works fine. Then I want to click on the button to change way of display comments. But want to do this without reloading a page. I click btn -> run JavaScript -> connect byt AJAX with API controller -> take back data from database ... And here I stuck
I have data in JSON but have no idea how to load them into my view instead a date loaded by Twig at the beginning.
That's a serious wall on my way to dynamic changes on web page. Thinking about:
Maybe you know how to solve that issue in more elegant way?
Upvotes: 1
Views: 3894
Reputation: 14025
It is not a Twig, but a JQuery concern. Here is an example.
Route:
my_symfony_route:
path: /get-filtered-list
defaults: { _controller: "CompanyMyBundle:Comment:getFilteredList" }
methods: POST
Controller
public function getFilteredListAction(Request $request)
{
$param1= $request->request->get('param1');
$param2= $request->request->get('param2');
$result = array();
//Fill $result with DB request
return new JsonResponse($result);
}
JQuery request
$.ajax({
type: 'POST',
url: "{{ path('my_symfony_route') }}",
data: { param1: 'value', param2: 'value' },
dataType: 'json',
success: function (data) {
//Handle your JSON data to update the DOM
$.each(data, function(index, element) {
$('#myDivId').append($('<div>', {
text: element.name
}));
});
}
});
Upvotes: 1