AppleForTheKing
AppleForTheKing

Reputation: 105

Javascript onclick: only works once

Here is the method I call, where I delete the event by id:

function delete_event(id)
{
    $.ajax({
        url: "/delete/"+id,
        type: "post",
        data: {  '_token': '{{csrf_token()}}' },
        success: function(data) {
            if (data.success == 1)
            {
                $("#alert").addClass("alert alert-success");
                $("#alert").innerText = "it worked";
                $("#alert").remove();
                $("alert").fadeOut(3000);
            }
            else
            {
                $("#alert").addClass("alert alert-danger");
                $("#alert").text("it didn't work");
                $("#alert").delay(3000).fadeOut(1000);
            }
        },
        error: function(data)
        {
            console.log("neieieiin");
            console.log(data);
        },
        complete: function(){}
    })
}

Here is the HTML-Code:

<div id="alert">
</div>

<table class="table table-striped">
    <tr>
        <th>Event Name</th>
        <th>Starting Date</th>
        <th>Location</th>
        <th>Actions</th>
    </tr>

    @foreach($events as $event)
        <tr id="{{$event->event_id}}">
            <td>{{$event->event_name }}</td>
            <td>{{$event->start_date}}</td>
            <td>{{$event->street_address}}</td>
            <td>
                <a>
                    <button onclick="delete_event({{$event->event_id}})" type="button" class="btn btn-default">
                    <i class="fa fa-times" aria-hidden="true"></i>
                    </button>
                </a>
            </td>
        </tr>
    @endforeach

</table>
@endsection

When I click the delete button it only once shows it worked/it didn't work. If I click it a second time nothing happens any suggestions?

Upvotes: 0

Views: 815

Answers (2)

AppleForTheKing
AppleForTheKing

Reputation: 105

$("#alert").fadeIn();
$("#alert").addClass("alert alert-danger");
$("#alert").text("it didn't work");
$("#alert").delay(3000).fadeOut(1000);

All I had to do is to fadeIn() the Element again. :D

Upvotes: 0

Sagar Arora
Sagar Arora

Reputation: 1773

You can use jquery on click method to solve this:

Change:

<button data-id="{{$event->event_id}}" type="button" class="btn btn-default delete_button">


jQuery(document).on("click",".delete_button",function(){

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

    $.ajax({

        url: "/delete/"+id,
        type: "post",
        data: {  '_token'           : '{{csrf_token()}}' },
        success: function(data) {
            if(data.success == 1)
            {
                //do as you want
            }

        },

    });

});

Upvotes: 1

Related Questions