Reputation: 2689
I would like to display data with jquery by clicking on a link. Here's the code but it lacks some code jquery to browse data and the code twig to display them.
this is the Twig:
<a href class="list">List</a>
<div id="travels">
// display data here
</div>
<script>
$(document).ready(function () {
$(".list").click(function () {
$.ajax({
type: 'POST',
dataType: 'json',
url: Routing.generate('travel_list_ajax'),
success: function () {
// rest of code
}
});
return false;
});
});
</script>
Action
public function listAjaxAction(Request $request)
{
if ($request->isXmlHttpRequest()) {
$em = $this->getDoctrine()->getManager();
$travels = $em->getRepository('AppBundle:Travel')->findAll();
$response = new JsonResponse();
return $response->setData(array('travels'=>$travels));
}
return null;
}
Upvotes: 0
Views: 3032
Reputation: 1327
If you are trying to load data into a twig template using Ajax, you can return the entire HTML markup for the Ajax call and then insert into the DOM. The steps are as given below. 1. In your template, specify a div in which you wish to display the data.Here I am assuming that you need to display a list. 2. Get the markup for the list through the Ajax call. 3. Insert the html returned by the Ajax call to the div in 1 using jquery.
For example, here I am trying to do a search on my users list and then change the data in the table accordingly. I am replacing the table markup inside the div with id user-list-div
according to the text in the search box.
Javascript part:
<script>
$(function(){
console.log('desperate for');
var searchField = $('#search-field');
var userListDiv = $('#user-list-div');
searchField.keyup(function(evt){
$.ajax({
url: '{{ path('admin_user_search') }}',
method: "POST",
data: "id=" + $(this).val() ,
dataType: 'html',
success: function(result, request) {
var parsedData =JSON.parse(result);
console.log(parsedData);
if(parsedData.status ==='success'){
console.log('hete');
userListDiv.empty();
userListDiv.html(parsedData.data);
}else{
//handle no result case
}
}
});
});
});
</script>
Controller Action
public function searchuserAction(){
$em = $this->getDoctrine()->getManager();
$request = $this->get('request');
$searchParameter = $request->request->get('id');
//call repository function
$entities = $em->getRepository('LBCoreBundle:User')->findUsersForname($searchParameter);
$status = 'error';
$html = '';
if($entities){
//get the HTML markup corresponding to the table
$data = $this->render('LBCoreBundle:User:ajax_template.html.twig', array(
'entities' => $entities,
));
$status = 'success';
$html = $data->getContent();
}
$jsonArray = array(
'status' => $status,
'data' => $html,
);
$response = new Response(json_encode($jsonArray));
$response->headers->set('Content-Type', 'application/json; charset=utf-8');
return $response;
}
Upvotes: 6