I just started using Ajax function in my work and I'm not very familiar with it. I have this problem that when I submit data, it submits without refreshing the page, but on a second time when trying to submit, the page refreshes before submitting. I've used the e.preventDefault() to prevent the page from refreshing but it is not working for me. It just seems there is something I'm not doing right.
This is my Ajax code
<!--AJAX PROCESS TO SUBMIT CHECKED COURSES-->
$(document).ready(function(){
loadNewCourse();
loadDelTable();
$('#submit').click(function(){
$('#form').submit(function(e){
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId : in_arr,
name : name,
email : email,
regno : regno,
level : level,
dept : dept,
semester : semester
},
success: function(data){
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Registration failed.", "error");
}
});
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#deleteCheck').click(function(){
$('#delform').submit(function(e){
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm){
if(isConfirm){
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id : id_arr,
regno : regno,
level : level
},
cache: false,
async: false,
success: function(data){
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Delete failed.", "error");
}
});
}else{
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
});
function loadNewCourse(){
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit : 1
},
success: function(disp){
$("#reveal").html(disp).show();
}
});
}
function loadDelTable(){
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel : 1
},
success: function(deldisp){
$("#showRegtbl").html(deldisp).show();
}
});
}
});
And this is the page displaying submitted data
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<span id="reveal"></span>
<!--Table to display courses registered-->
<span id="showRegtbl"></span>
</div>
</div>
I've been stuck in this for more than 3days now. Can anyone here help me out pls?
I think you misunderstood the submission of the form and even handling.
The default action of the form ie submit can be done with input type="submit" or <button>
The default
<h2> Form default action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit">
</form>
To prevent form's default action you can do 2 things.
Avoid using type="submit" or button
Do something like this
function customForm(){
alert("Hey this is custom handler, dont worry page will not refresh...!");
}
<h2> Form with custom action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="button" value="submit" onclick="customForm()">
</form>
Use event.preventDefault()
$('#myform').submit(function(e){
e.preventDefault();
alert("custom handler with preventDefault(), no reload no worries...!");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2> Form with custom handler using preventDefault() </h2>
<form id="myform" action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit" onsubmit="customForm(this)">
</form>
For any queries comment down.
Calling $("#form").submit(function() { ... }) creates a handler for the next time the form is submitted. Doing this inside the handler for $("#submit").click() is not correct. Clicking the submit button will establish a handler for the next submission, but then the default action will submit the form immediately, which refreshes the page. Putting e.preventDefault() inside the click handlers would prevent the reload, but then you would have to click twice to submit the form (and this wouldn't actually work, because the default action of a submit button is to trigger the submit event, and you're preventing that).
Just create submit handlers for each form, without doing it inside a click handler.
$(document).ready(function() {
loadNewCourse();
loadDelTable();
$('#form').submit(function(e) {
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId: in_arr,
name: name,
email: email,
regno: regno,
level: level,
dept: dept,
semester: semester
},
success: function(data) {
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Registration failed.", "error");
}
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#delform').submit(function(e) {
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id: id_arr,
regno: regno,
level: level
},
cache: false,
async: false,
success: function(data) {
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Delete failed.", "error");
}
});
} else {
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
function loadNewCourse() {
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit: 1
},
success: function(disp) {
$("#reveal").html(disp).show();
}
});
}
function loadDelTable() {
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel: 1
},
success: function(deldisp) {
$("#showRegtbl").html(deldisp).show();
}
});
}
});
If you had multiple submit buttons in the same form you would instead assign click handlers to each button, but not create submit handlers for the form.
Thanks everyone for the assistance. I did some debugging on my end and was able to fix the issue by removing the form tags from the Add and Delete scripts and then include them in the page displaying the submitted data.
Like this...
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<form id='form' action='POST' href='#'>
<span id="reveal"></span>
</form>
<!--Table to display courses registered-->
<form id='delform' action='POST' href='#'>
<span id="showRegtbl"></span>
</form>
</div>
</div>
Is there a more proper way to do this or this is just okay? Thank you for the help so far.
Hello guys I'M having an issue with my sweetalert delete confirmation. When I click on "Yes Delete it!" nothing happens and there are no errors showing in my console please guys I seriously need help this has kept me on deck for a long time now. I really be grateful if I get quick responses.
This is my blade.php
<button onclick="deleteConfirmation({{$poster->id}})" type="button" class="btn btn-danger delete-confirm offset-md-2">Delete</button>
<script type="text/javascript">
function deleteConfirmation(id) {
swal({
title: "Delete?",
text: "Are you sure you want to delete this?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel!",
reverseButtons: true
}).then(function (e) {
if (e.value) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'DELETE',
url: "{{ url('delete-post') }}" + '/' + id,
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
}
});
} else {
e.dismiss;
}
}, function (dismiss) {
return false;
})
}
</script>
And here is my controller
public function deletepost($id)
{
dd($id);
DB::table('posters')->where('id', $id)->delete();
return back()-> with('post_add', 'Post deleted Successfully');
}
And my route
Route::delete ("/delete-post/{id}", [PosterController::class, "deletepost"])->name("poster.delete");
when i click the button confirm on swal nothing happens, i dont khow if the problem is the ajax code
or somthing else
but when i delete the ajax code from the swal code it works fine and shows the sweetalert so i think the probleme comes from ajax
<script>
function deleteData(id) {
swal({
title: "Suppression",
text: "Veuillez confirmer la suppression",
type: "warning",
showCancelButton: true,
confirmButtonText: "Confirmer",
cancelButtonText: "Annuler",
reverseButtons: true
}.then(function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "DELETE",
url: "{{url('eventment/type')}}/" + id,
data: {
_token: CSRF_TOKEN
},
dataType: "JSON",
success: function (results) {
if (results.success === true) {
swal("Done!", results.message, "success");
} else {
swal("Error!", results.message, "error");
}
} //success
});
})
) //swal
} //deleteData
</script>
Delete button
<button class="btn btn-danger" onclick="deleteData({{$type->id}})" >Supprimer</button>
route file
Route::delete('eventment/type/{id}','TypeController#destroy')->name('type.destroy');
controller
public function destroy($id)
{
$type = EventType::where('id', $id)->delete();
return redirect()->to(route('admin.type.index'))->withFlashSucces('Le Type A Bien Etait Supprimé');
}
You can do it without ajax.first your button make it as a form
<form id="del_event" action="{{ route('type.destroy',$type->id) }}" method="post"style="display: inline;">
{!! method_field('delete') !!}
{{ csrf_field() }}
<button class="btn btn-danger" type="submit" id="del_id">Supprimer</button>
</form
Button has a id "del_id" when it click call a function below there
<script>
$("#del_id").on('click', function (e) {
e.preventDefault();
swal({
title: "Suppression",
text: "Veuillez confirmer la suppression",
type: "warning",
showCancelButton: true,
confirmButtonText: "Confirmer",
cancelButtonText: "Annuler",
}).then((result) => {
if(result) {
$("#del_event").submit();
}
}
)
;
});
</script>
Your destroy function
$type=EventType::find($id);
$type->delete();``
I want to integrate sweetalert with my project. but I'm having the following error.
this is my html code
<script type="text/javascript">
$('.bank').on('click', function (e) {
e.preventDefault();
var id = $(this).data('id');
const swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: 'btn btn-success',
cancelButton: 'btn btn-danger'
},
buttonsStyling: false,
})
swalWithBootstrapButtons.fire({
title: 'Are you sure?',
text: "Payment method Bank Transfer Mandiri!",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes!',
cancelButtonText: 'No, cancel!',
reverseButtons: true
},
function(isConfirm) {
if (isConfirm){
$('#my-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "{{ route('payment') }}",
data: $('#my-form').serialize(),
success: function (data) {
//
}
});
});
}
});
});
</script>
I've been looking for solutions to this problem quite a long time, but I still can not solve it
please help me. thx..
Please include the CDN available for sweatalert.js .
As I don't see any erros above,
I suggest you to add the following code before script .
https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js
I have linked sweetalert plugin for my confirmation message. But it's not getting the confirmation command (onclick yes/confirm button).
This is my delete button:
<a id="demoSwal" href="{{ route('setting.website_type.destroy', ['id' => $websiteType->id]) }}" class="btn btn-light btn-sm btn-delete demoSwal" data-toggle="tooltip" data-placement="top" title="Delete This Type"><i class="far fa-trash-alt"></i></a>
This is My JS Code:
$(document).ready(function(){
$('.demoSwal').click(function(){
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your Data file has been deleted.", "success");
} else {
swal("Cancelled", "Your Data file is safe :)", "error");
}
});
});
});
This is my Controller Code:
public function destroy($id)
{
$delete_website_type = WebsiteType::find($id);
$delete_website_type->delete();
return redirect()->back();
}
Please Give me the solution...
you have to put .then()
let id = $("#your_id").val();
swal({
title: "Are you sure?",
text: "You will not be able to recover this file!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
}).then((isConfirm) => {
if(isConfirm) {
//you can just use fetchAPI
fetch(`route_to_your_destroy_method/${id}`)
.then(response => response.json()
.then(result => {
//your result
if (result == 'success') {
//alert success
}else {
//alert fail
}
}).catch(err => {console.log(err)});
}
});
and in your destroy method
$delete_website_type = WebsiteType::find($id)->delete();
if(delete_website_type) {
$message = 'success';
}else {
$message = 'fail';
}
return json_encode($message);
Give it a try
for delete button:---
<i class="far fa-trash-alt"></i>
in Jquery
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('/setting/website_type/destroy')}}",
data: {id:id},
success: function (data) {
//
}
});
});
});
and
public function destroy(Request $request)
{
$delete_website_type = WebsiteType::find($request->id)->delete();
return redirect()->route('website.index')
->with('success','Website deleted successfully');
}
i have updated my answer try this one.