Matej Matej - 3 months ago 10
jQuery Question

ajax request works only once in laravel

at first my ajax request work good, but after loaded partial page with ajax request then ajax stop working(not only ajax, but entire action on element), why?

My html code:

<td>

@foreach($file_defects[$revision->revision_id] as $file_defect)
<a href='http://localhost/sponaDP/laravel/public/docs/revision_intervals/{{ $revision->rev_interval_id . '/' . $revision->date_of_revision->format('d.m.Y') . '/defects/' .
$file_defect->getFilename() }}' target="_blank">
{{$file_defect->getFilename()}}
</a>
<a class="destroyFileFromRevision" id="{{$file_defect->getPathname()}}" style='color:red;'><span style="display:none;" class="rev">{{$revision->revision_id}}</span><span class='glyphicon glyphicon-remove'></span></a>
<br>
@endforeach
</td>


My ajax:

$(".destroyFileFromRevision").click(function () {
var filename = this.id;
var rev = $(this).children('.rev').text();
$.ajax({
type: "POST",
url: "http://localhost/sponaDP/laravel/public/revisions/destroy-file",
data: 'filename=' + filename + '&rev=' +rev,
beforeSend: function () {
$(".destroyFileFromRevision").parent('td').html(
"<i class='fa fa-spinner fa-spin' aria-hidden='true' \n\
></i>");
},
success: function (data) {
$(".fa").parent('td').html(data);
}
}, 'json');
});


These are html data returned by ajax request ( url: ... /destroy-file):

@foreach($file_defects[$revision->revision_id] as $file_defect)
<a href='http://localhost/sponaDP/laravel/public/docs/revision_intervals/{{ $revision->rev_interval_id . '/' . $revision->date_of_revision->format('d.m.Y') . '/defects/' . $file_defect->getFilename() }}' target="_blank">
{{$file_defect->getFilename()}}
</a>
<a class="destroyFileFromRevision" id="{{$file_defect->getPathname()}}" style='color:red;'><span class='glyphicon glyphicon-remove'></span></a>
<br>
@endforeach

Answer

You must make element always live by this way $(".destroyFileFromRevision").click(function ()
To
$(document).on('click', '.destroyFileFromRevision', function()