Justin Cefai
Justin Cefai

Reputation: 151

Problem with ajax request for delete function

I have a "todo" application that I've added a delete button to. The application is already set up to post via an ajax request, but the delete button causes a page re-load after it is clicked. I feel like preventDefault should... well prevent that from happening, but it doesn't. Any advice would be much appreciated!

function to list tasks

function taskHtml(task) {
        var checkedStatus = task.done ? "checked" : "";
        var liClass = task.done ? "completed" : "";

        var liElement = '<li id="listItem-' + task.id + '" class="' + liClass + '">' +
        '<div class="view"><input class="toggle" type="checkbox"' + " data-id='" +
        task.id + "'" + checkedStatus + ' /><label>' + task.title + 
        '</label><a class="destroy" rel="nofollow" data-method="delete" href="/tasks/' + task.id + 
        '"></a></div></li>';

        return liElement;   

    }

delete task function

function deleteTask(e) {
        e.preventDefault();

        var itemId = $(e.target).data("id");

        $.ajax("/tasks/" + itemId, {
            _method: "DELETE",
        }).success(function(data) {
            var liHtml = taskHtml(data);
            var $li = $("#listItem-" + data.id);
            $li.replaceWith('');
        });
    }


    $.get("/tasks").success( function( data ) {
        var htmlString = "";
        $.each(data, function(index, task) {
            htmlString += taskHtml(task);
        });

        var ulTodos = $('.todo-list');
        ulTodos.html(htmlString);

        $('.toggle').change(toggleTask);

        $('.destroy').click(deleteTask);
    });

Upvotes: 0

Views: 118

Answers (1)

gaheinrichs
gaheinrichs

Reputation: 610

Remove the href from the <a> tag. I will recommend to change this to a <button> since you are not taking the user to any other page.

I also suspect this will not work:

var itemId = $(e.target).data("id");

Try changing it to:

var itemId = $(this).parent().data("id");

Upvotes: 1

Related Questions