onclick event only work on first <td> child (laravel foreach) - javascript

I make button action on every data from table row. every row produces using foreach laravel blade template. the event will trigger a Javascript action to delete the data. but on my case the button only work on first row data.
here my Javascript and html code :
function hapusFaskes(kode){
var kodeStr = kode.toString();
var mes = confirm('Yakin Faskesnya mau di Hapus?');
alert(kode);
if (mes == true){
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:'{{url('deleteFaskes')}}'+'/'+kode,
type:'get',
success: function (r){
console.log(r);
alert(r);
location.reload();
}
});
}
}
<tbody id="hasil-tabel">
#foreach ($faskes as $val)
<tr>
<td>{{$val->kode}}</td>
<td>{{$val->nama}}</td>
<td>{{$val->jenis}}</td>
<td>{{$val->alamat}}</td>
<td>{{$val->notelp}}</td>
<td>{{$val->jambuka}}</td>
<td>
<a href="{{url('editfaskes').'/'.$val->kode}}" class="btn btn-default" >Edit</a>
Hapus
</td>
</tr>
#endforeach
</tbody>
I don't know if there are something wrong on my code, if you know something wrong, please inform me and that will be a big help for me if you know something wrong on my code. thanks

Try using the below code with form action along with sweet alert for confirmation.
<form action="{{ url('deleteFaskes/'. kode) }}" method="POST" class="btn-inblock-laravel">
{!! method_field('delete') !!}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<a class="btn btn-danger btn-icon btn-xs tip" type="button" onclick="commonDelete(this)"><i class="icon-remove3"></i></a>
</form>
// include sweet alert js in assets folder
<script src="{{ asset('assets/js/sweetalert.min.js') }}"></script>
<script>
function commonDelete(element) {
swal({
title: "Are you sure?",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function () {
element.parentElement.submit();
setTimeout(function () {
swal({
title: "Deleted!",
text: "",
type: "success",
showConfirmButton: false
});
}, 2000);
});
}
</script>

Related

How do I stop ajax call from refreshing my page?

<form id="review" method="post">
{% csrf_token %}
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<span class="icon text-white-50">
<i class="fas fa-poll-h"></i>
</span>
<span class="text">Fetch Reviews</span>
</button>
</form>
This is my html form on a Django rendered page
<script type="text/javascript">
$(document).on('submit','#review'.function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
type:'POST',
URL:'/reviews/',
data:{
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
beforeSend:function() {
$('#loader').removeClass('hidden');
},
complete : function() {
$('#loader').addClass('');
}});
return false;
});
This is the ajax function on the page.
The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both
e.preventDefault()
and
e.stopPropagation()
but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you!
To make this work change this part of code:
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
Like that:
<button type="button" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<button type="submit" id="submit_sbtn" class="d-none">
The submit button is not necessary.
Then change your script to send an ajax request to $('#sbtn') click event. And then submit your form.
$(document).on('submit','#review', function() {
$('#loader').removeClass('hidden');
$.ajax({
method: "POST",
type: "POST",
url: "/reviews/",
data: {
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
}
}).done( function( msg ) {
$('#loader').addClass('');
console.log(msg)
}).fail( function(error) {
console.log(error)
})
return false;
})

Document.getElementById(...) is Null in Laravel View

Message in console
TypeError: document.getElementById(...) is null.
Blade (containing a button to delete)
<td>
<i class="fa fa-pencil"></i>
<button type="button" class="btn btn-danger btn-sm"
onclick="deleteSaleItem({{ $sale->id }})">
i class="fa fa-trash"></i>
</button>
<form id="delete-form-{{ $sale->id }}" action="{{ route('secretary.sales.destroy.item',$sale->id) }}" method="POST"
style="display:none;">
#csrf
#method('DELETE')
</form>
</td>
Javascript implementation
<script>
function deleteSaleItem(id){
const swalWithBootstrapButtons = swal.mixin({
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
buttonsStyling: false,
})
swalWithBootstrapButtons({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, delete it!',
cancelButtonText: 'No, cancel!',
reverseButtons: true
}).then((result) => {
if (result.value) {
event.preventDefault();
document.getElementById('delete-form-'+id).submit();
} else if (
// Read more about handling dismissals
result.dismiss === swal.DismissReason.cancel
) {
swalWithBootstrapButtons(
'Cancelled',
'Your data is safe :)',
'error'
)
}
})
}
</script>
I need to know what is wrong with this code which results in null. Thank You.
There is only one getElementById in your code.
document.getElementById('delete-form-'+id)
So, it might be the 'id' variable is empty or null and the element you retrieve become null.
Try debugging or console.log your 'id' variable just before document.getElementById code to see what happen to your variable.

How to reset form with sweetalert2

I am using SweetAlert2. I want when user click on Reset button a popUp of SweetAlert appears for confirmation. I had done this already.
HTML
<form id="storyForm" action="ephp/storyPublish.php" method="POST">
<input type="text" name="userName" />
<input type="Email" name="userEmail" />
<button type="submit">Publish</button>
<button type="reset" class="model_img" id="sa-warning">Reset</button>
</form>
JS
$("#storyForm").on('reset', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Do you really want to reset?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Go on!',
cancelButtonText: "Ops no!",
}).then(function(isConfirm) {
swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
}, function() {
form.reset();
});
},function(dismiss) {
if(dismiss == 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
PopUp is appearing but form is not reseting, what's wrong with this Javascript?
Here is the Fiddle
Hi I was able to get your form to reset but not using your form.reset() function, I was able to get it to work by giving the inputs ids and then handling the reset using sweetalerts result.
HTML
<form id="storyForm" action="ephp/storyPublish.php" method="POST">
<input type="text" name="userName" id="userName" /> <!--added the id here-->
<input type="Email" name="userEmail" id="userEmail" /> <!--added the id here-->
<button type="submit">Publish</button>
<button type="reset" class="model_img" id="sa-warning">Reset</button>
</form>
JavaScript
$("#storyForm").on('reset', function(e) {
var form = $(this);
e.preventDefault();
swal({
title: "Are you sure?",
text: "Do you really want to reset?",
type: "warning",
showCancelButton: true,
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Go on!',
cancelButtonText: "Ops no!",
}).then((result) => {
if (result.value) {
$("#userName").val("");
$("#userEmail").val("");
swal(
'Reset!',
'Your form has been reset.',
'success'
)
/*swal({
title: 'Success!',
text: 'Invoice created! Go to the invoice tab to pay it.',
type: 'success'
});*/
// result.dismiss can be 'cancel', 'overlay',
} else if (result.dismiss === 'cancel') {
swal("Cancelled", "Invoice not created!", "error");
}
});
});
NOTE - I commented out your Success swal as it wasn't adding an invoice but if you want it to do so just un comment it and remove the sweetalert above it.
Here is a jsFiddle
I hope this helps good luck!

laravel 5.5 Sweet alert in submiting form

I have a form. I need to activate when click the submit button. how can id do this in laravel blade.
my form
<form action="{{ route('backend.tasks-send-email.store') }}" method="POST">
{{ csrf_field()}}
<label for="propertyName">Email To</label>
<input class="form-control" id="editteamName" name="teamName" type="text" id="teamName" required="true" value="" disabled>
<label for="maker-content">Message</label>
<textarea id="maker-content" name="emailContent" ></textarea>
<button type="submit" class="btn btn-primary" id="submit">button</button>
</form>
Javascipt codes
$(document).on('click', '[#submit]', function (e) {
e.preventDefault();
var data = $(this).serialize();
swal({
title: "Are you sure?",
text: "Do you want to Send this email",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, send it!",
cancelButtonText: "No, cancel pls!",
}).then(function () {
swal(
'Success!',
'Your email has been send.',
'success'
)
});
return false;
});
Try this one. in you're form add id attribute.
in your javascript when form with this id attribute is submit the sweet alert is activated.
Form
<form action="{{ route('backend.tasks-send-email.store') }}" method="POST" id="form">
{{ csrf_field()}}
<label for="propertyName">Email To</label>
<input class="form-control" id="editteamName" name="teamName" type="text" id="teamName" required="true" value="" disabled>
<label for="maker-content">Message</label>
<textarea id="maker-content" name="emailContent" ></textarea>
</form>
javascript
$(document).on('submit', '[id^=form]', function (e) {
e.preventDefault();
var data = $(this).serialize();
swal({
title: "Are you sure?",
text: "Do you want to Send this email",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, send it!",
cancelButtonText: "No, cancel pls!",
}).then(function () {
$('#form').submit();
});
return false;
});

Re-execute php loop with ajax

I am using laravel 5.4.
I have many clinics in my database. I just want to retrieve all the clinics and put a delete button on each clinic. Whenever a user clicks the delete button the the clinic should be removed from the database and clinics should be updated in the front end.
This is my code.
#foreach($doctor->clinics as $clinic)
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
#endforeach
I don't want to reload the page whenever a clinic is removed. So, how can I re-execute this loop, whenever a clinic is successfully removed using ajax.
A better way to approach this might be to just remove the row using javascript. In the same function where you hide the loader, you can also remove the form from the dom.
Like so:
#foreach($doctor->clinics as $clinic)
<div id="clinic{{$clinic->id}}">
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
// Fade out and remove the form element
$("#clinic{{$clinic->id}}").fadeOut(300, function() {
$(this).remove();
});
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
</div>
#endforeach
This way you don't have to write another ajax function.

Categories

Resources