blahblah blahblah - 11 months ago 115
Twig Question

Symfony: pass parameter to Ajax url

I am trying to figure out how to enable/disable user with checkbox without page reload.

index.html.twig

<table>
<thead>
<tr>
<th>UserName</th>
<th>Enabled</th>
</tr>
</thead>
<tbody>
{% for user in users %}
<td><a href="{{ path('user_show', {'id': user.id}) }}">
{{ user.username }}</a>
</td>
<td><input id="user_enable_{{ user.id }}" onclick="enabledChange({{ user.id }})"
type="checkbox" {% if user.enabled %}checked{% endif %}/>
</td>
{% endfor %}
</tbody>
</table>

<script>
var changePath = {{ path('user_enable_change', {'id': user.id}) }};

function enabledChange(id)
{
var value = $(this).val();
console.log('value: ' + value);
$.ajax({
type: "POST",
url: changePath,
async: true,
data: { },
success: function () {
console.log('success');
}
});
}
</script>


UserController

/**
* @Route("/enable/{id}", name="user_enable_change")
*/
public function userDisableAction(User $user) {

if($user->isEnabled()){
$user->setEnabled(false);
}else {
$user->setEnabled(true);
}

try {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
}
catch(\Exception $e) {
return new JsonResponse('error');
}

return new JsonResponse('success');

}


Question

How can I set corresponding user id to enabledChange function and change checked state depending on user state?

Answer Source

You need to add quotes to your variables, and pass changePath as an argument:

onclick="enabledChange('{{ user.id }}', '{{ path('user_enable_change', {'id': user.id}) }}')"

then:

function enabledChange(id, changePath) {
    var value = $(this).val();
    console.log('value: ' + value);
    $.ajax({
        type: "POST",
        url: changePath,
        async: true,
        data: { },
        success: function () {
            console.log('success');
        }
    });
}

I hope this will help.