CRUD – Add and Delete not working one after other if page is not refreshed

I have one annoying problem that I am not able to solve.

I am generating CRUD operations in my Symfony project. I made an AJAX request for Add method which works as it should.

After that I have created AJAX request for Delete method.

When I add my new entity object the table is reloaded without page refresh.

Problem is that if I click delete after it’s added it throws an error that ID is not found.

/**
 * @Route("/user/{id}", name="user_delete", options={"expose"=true})
 */
public function delete($id)
{
    $em = $this->getDoctrine()->getManager();

    $$user = $em->getRepository(User::class)
        ->findOneby(['id' => $id]);

    if (!$user) {
        throw $this->createNotFoundException('No User found for id '.$id);
    }

    $em->remove($user);
    $em->flush();

    return $this->json(["message" => "SUCCESS"]);
}

So, for example I have added entity with ID = 2 . DIV is reloaded. Now I click in delete of 2 and it’s says:

No user found for id 1

Problem is it always fatches the last ID I deleted after page refresh.

Now, if I refresh the page and then try delete it will catch ID = 2 and delete it. Now, I add ID = 3 without refreshing the page and it will throw:

No user found for id 2

I think maybe it has to do with my add form:

Add form:

$('#form-submit').on('click', function (e) {
e.preventDefault();


    $.ajax({
        type: "POST",
        url: '/subscription/add',
        data: $('form#subscription-form').serialize(),
        processData: false,
        success: function () {
            $("#user-table").load(location.href + " #user-table");
            $('#addUser').modal('hide');
            displayNotif('success', 'check', 'User created successfully');
        },
        error: function (xhr, status, error) {
            var ErrorMessage = JSON.parse(xhr.responseText);
            $('#general-error').html(ErrorMessage.message);
        }
    });
});

Can someone please help?

$(document).ready(function () {

$('.user_delete').on('click', function () {
    let removeUrl = $(this).attr('data-remove-url');
    $('.remove-user').attr('data-remove-url', removeUrl);
});

$(".remove-user").click(function (e) {
    let removeUrl = $(this).attr('data-remove-url');
    e.preventDefault();
    $.ajax({
        url: removeUrl,
        type: 'DELETE',
        success: function()
        {
            $("#user-table").load(location.href + " #user-table");
            $('#confirmDelete').modal('hide');
            displayNotif("danger", "warning", "User deleted successfully");
        }
    });
});
});

I am adding everything so you can get an idea of what I am doing:

<a href data-toggle="modal" data-target="#confirmDelete" data-remove-url="{{ path('user_delete', {'id':user.id}) }}" class="btn user_delete">x</a>

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *