简体   繁体   中英

Symfony 3/4 : delete a table row from a database through AJAX

I am a little bit stuck on my Symfony code.

Let me explain ,

I have a todo-list table in my database containing :

  • An ID called : id
  • A name field called : todo
  • And 3 others fields that don't matter : "completed", "created_at", "updated_at" .

Before going further : here is my codes ,

The concerned Controller :

  /**
 * @Route("/todos/delete/{id}", name="todo.delete", methods={"POST"})
 * @param Todo $todo
 * @param ObjectManager $manager
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\RedirectResponse
 */
public function delete(Todo $todo, ObjectManager $manager, Request $request)
{
    $manager->remove($todo);
    $manager->flush();

    if ( $request->isXmlHttpRequest()) {
        return $this->redirectToRoute('todo.home', [
            'id' => $todo->getId()
        ]);
    }
    throw $this->createNotFoundException('The todo couldn\'t be deleted');
}

The view :

{% extends 'base.html.twig' %}

{% block title %}Todos{% endblock %}

{% block content %}
<br>
<form action="{{ path('todo.create') }}" method="post">
    <input type="hidden" name="token" value="{{ csrf_token('todo-create') }}"/>
    <label for="todo">Todo</label>
    <input type="text" id="todo" name="todo" class="form-control input-group-lg" placeholder="Create a new todo">
</form><br>
{% for todo in todos %}
    {{ todo.todo }}
    <a href="{{ path('todo.update', {'id': todo.id}) }}" class="btn btn-info btn-sm">Update</a>
    <a href="{{ path('todo.delete', {'id': todo.id}) }}" class="btn btn-danger btn-sm js-delete-todo" id="{{ todo.id }}">x</a>
    {% if todo.completed %}
        <a href="{{ path('todo.completed', {'id': todo.id}) }}" class="btn btn-success btn-sm">Completed !</a>
    {% else %}
        <a href="{{ path('todo.completed', {'id': todo.id}) }}" class="btn btn-warning btn-sm">Mark as completed</a>
    {% endif %}
    <hr>
{% endfor %}
{% endblock %}

We focus on :

<a href="{{ path('todo.delete', {'id': todo.id}) }}" class="btn btn-danger btn-sm js-delete-todo" id="{{ todo.id }}">x</a>

The JavaScript :

$(document).ready(function () {
$('.js-delete-todo').on('click', function (e) {
    e.preventDefault();

    var url = $(this).attr('href');
    delTodo(url);

    function delTodo(url) {
        $.ajax({
            type: "POST",
            url: url
        }).done(function (data) {
            $('#id').remove();
        }).fail(function () {
            alert('Could not be deleted');
        });
     }
  });
});

Actually ,

Everything seems to work : it does a POST ajax request, and delete the row in my table in my database.

The only issue is that I have to hit F5 to see it.

How can I make it work without reloading the page nor hitting the F5 hotkey?

In your symfony code you should return JSON format like here . Wrap your todo in container like this

{% for todo in todos %}
  <div id="todo-{{todo.id}}">
    // your todo staff here 
  </div>
{% endfor %}

Then change your javascript to

function delTodo(url) {
    $.ajax({
        type: "POST",
        url: url
    }).done(function (data) {
        var id = JSON.parse(data).id;
        $('#todo-' + id).remove();
    }).fail(function ()
        alert('Could not be deleted');
    });
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM