用javascript(Ajax)更新Symfony

问题描述 投票:2回答:1

在我的项目中,我的表中有一个选择框,应该更新数据库中的选择框值更改,我这样做了,我得到选择的选项的值和应该更新的ID,问题是我的控制器没有修改数据库中的值

public function editAction(Request $request, Client $client)
{
    $deleteForm = $this->createDeleteForm($client);
    $editForm = $this->createForm('AppBundle\Form\ClientType', $client);
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid()) {

        $status = $request->request->get('status');
        $client->setStatus($status);
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('client_index');
    }

    return $this->render('client/edit.html.twig', array(
        'client' => $client,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
    ));
}

在我的js

function update(id, status){
var statusValue = {'status':status};
var path = Routing.generate('client_edit',{'id': id});

$.ajax({
    type: "POST",
    url: path,
    data: statusValue
});

}

在我的表中的客户端索引

<td>
<select id="status" name="status" onchange="update({{ client.id }}, this.value)">
    <option {% if client.status is empty %}
    selected
    {% endif %}>Status</option>

    <option {% if client.status == 'Envoyer') %}
        selected
    {% endif %}
            value="Envoyer">Envoyer</option>
    <option {% if client.status == 'Annuler') %}
        selected
    {% endif %}
            value="Annuler">Annuler</option>
    <option {% if client.status == 'Rejetter') %}
        selected
    {% endif %}
            value="Rejeter">Rejeter</option>
</select>

所以在这里,我得到选择选项的id和值,但我的数据库中没有更新,谁可以执行它来更新我的数据库,谢谢!

symfony twig
1个回答
1
投票

问题来自这条线

$editForm->isSubmitted() && $editForm->isValid()

因为您的表单从未提交过。如果您不需要表单验证,请将此行替换为:

//Check if it's an ajax request
if($request->isXmlHttpRequest()){
//you can get status directly with this
$request->get('status');
//Do some stuff... 
© www.soinside.com 2019 - 2024. All rights reserved.