I have a simple showAction to show a user's information:
/**
* @Route("/user/{id}", name="show_user", options={"expose"=true})
* @Method("GET")
*
* @param User $user
* @return \Symfony\Component\HttpFoundation\Response
*/
public function showAction(User $user)
{
return $this->render('user/showUser.html.twig', array(
'user' => $user,
));
}
I try to get the information with AJAX to display it in a seperate div:
$('.showUser').click(function (e) {
var getUrl = Routing.generate('show_user', {'id': $(this).attr('id')});
e.preventDefault();
$.ajax({
url: getUrl,
success: function (data) {
$("#userdetails").html(data);
}
});
});
My list of users overview in html:
<table class="table-title table table-striped table-bordered">
<thead>
<tr>
<th class="col-md-2">Name</th>
<th class="col-md-1">Age</th>
<th class="col-md-1">Actions</th>
</tr>
</thead>
<tbody>
<tr>
{% for user in users %}
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>
<button id="{{ user.id }}" type="button" class="deleteUser btn btn-lg btn-danger">Delete</button>
<button id="{{ user.id }}" type="button" class="showUser btn btn-lg btn-primary">Show</button>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="displayUser col-sm-4">
{% include 'user/showUser.html.twig' %}
</div>
And my showUser template to display the selected user:
<div id="userdetails">
{{ dump(user) }}
</div>
What currently is happening is that when I load the page, the {{ dump(user) }}
contains an array of all the users, and is not empty. When I then click on the show button to display the one user's information the {{ dump(user)}}
does change to show the correct information.
Also when I change {{ dump(user) }}
to be {{ user.name }} - {{ user.age }}
, and reload the page I get the error:
Key "name" for array with keys "0, 1" does not exist in user/showUser.html.twig at line 2
Can somebody help me? Explain to me what I am doing wrong? I think there is also something wrong with my ajax call, I have never used ajax before, and I have created this based on samples I managed to find, but further than this I don't get.
All I want is to display the user's information in a div when clicking on the user's show button.