Hi I have a problem when I run the code a second code will not run. However when the second code to be executed each time the code still runs. The first code adds value to the database and database re-runs and the second code amount removed from the table, but only the amount that was removed from the environment.
my problem is jQuery does not execute on div loaded with ajax!
How to bind click event on dynamically added element for this code? How to solve this problem??
first code:
<script>
$('#submit').on('click', function (e) {
e.preventDefault();
var data = $('#create').serialize();
$.ajax({
headers: {
'X-CSRF-Token': $('input[name="_token"]').val()
},
type: 'post',
url: '{!! URL::route('category') !!}',
data: data,
success: function (data) {
var dataDelete = 'category/' + data.id + '/delete';
var dataCat = data.cat;
var dataId = data.id;
$('#append').load('loadCat');
},
error: function (xhr, status, errorThrown) {
alert(JSON.parse(xhr.responseText).category[0]);
}
});
jQuery("#create").val('');
});
</script>
Second:
<script>
$('[data-delete]').on('click', function (e) {
e.preventDefault();
var this_ = $(this);
var token = $('input[name="_token"]').attr('value');
var id = $(this).data("id");
$.ajax(
{
url: "{{ url('/category') }}" + '/' + id + '/delete',
type: 'post',
dataType: "JSON",
data: {"id": id, '_token': token},
success: function (data) {
$(this_).parent().parent().remove();
}
});
console.log("It failed");
});
</script>