I have this function in my controller:
[HttpPost]
public IActionResult DeleteBooking(string bookingId)
{
Console.WriteLine("id: " + bookingId);
DeleteResult<IBooking> deleteResult = bookingDomain.DeleteBooking(Guid.Parse(bookingId));
return View("Index");
}
And in my View I need to delete a booking using a button. So I made a javascript onclick function. It goes to the function in my controller but it passes null as parameter instead of the id as string idk what to do anymore...
function deleteBooking(bookingId) {
console.log(bookingId); // this works
Swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
$.ajax({
type: 'POST',
url: '/Booking/DeleteBooking/', // the URL of the controller action method
data: bookingId, // optional data
success: function (result) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
},
error: function (req, status, error) {
Swal.fire(
'Error!',
'Your file could NOT be deleted.',
'error'
)
}
});
}
})
}
The console.log(bookingID) shows me the right id but in the controller function I just get null.
Try updating the data portion of your ajax call to look like this:
$.ajax({
type: 'POST',
url: '/Booking/DeleteBooking/', // the URL of the controller action method
data: { bookingId: bookingId } , // optional data
success: function (result) {
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
},
error: function (req, status, error) {
Swal.fire(
'Error!',
'Your file could NOT be deleted.',
'error'
)
}
});
When passing data to controller via Ajax, the data must be sent as key value pairs as follows:
data: { "bookingId": bookingId }
Key must be same as the parameter name in the controller.
Related
I have used Django2 to develop a web app.
I frontend, after the ajax call, the network tab on chrome dev does show the 200 status code, but I did not see any alert box. my app stuck at this line for waiting json: const msg_json = await response.json(); , the following alert does not execute
async function myFunction() {
Swal.fire({
title: '',
text: "Do you want to confirm entries?",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes',
cancelButtonText: 'No'
}).then(
async(result) => {
if (result.value) {
$.ajax({
url: '/content_checklist_name_url/',
type: 'POST',
data: $(this).serialize(),
cache: false,
success: function(data) {
var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
$('#myform_1').remove();
$('#ajax_data').prepend(comment_html);
$('#myform_input').val('');
},
});
const response = await fetch({ % url 'bms:content_checklist_name_url' %
});
const msg_json = await response.json();
alert(msg_json.responseText)
let a = msg_json;
if (a === "Duplicate Entry. This Course Code already exists.") {
Swal.fire({
title: '',
text: 'Duplicate Entry. This Course Code already exists.',
type: 'error',
})
} else {
Swal.fire({
title: '',
text: 'Entries have been saved.',
type: 'success',
})
}
// },
// failure: function(data)
// {
// alert('Got an error dude');
// }
// });
} else {
window.stop();
}
}
)
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>
backend view.py:
#csrf_exempt
def content_checklist_name_url(request):
if request.method == 'POST':
...
msg = "success"
obj = {"msg": msg}
context = {'msg_json': json.dumps(obj)}
return render(request, 'bms/main.html',context=context)
I got the error in the console: VM355:4 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 3
no alert box shows.
How could I check where goes wrong?
Your view is waiting for a POST and you are sending a GET so this branch won’t be executed. Also, submitting a form by html, make the browser change pages so as the form is submitted, the ajax won’t be called.
I'm trying to show the sweet alert in my DELETE FEATURE but sadly my code now is not working I already search for similar feature I see some but it not help me thought. Here is my code
<a id="<?php echo $id;?>" value="<?php echo $id;?>" name="delete" onclick="archiveFunction(this.id)">
<i class="glyphicon glyphicon-trash text-red"></i></a>
And this is my ajax request
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
$('#reloadpage').click(function() {
location.reload(true);
});
function archiveFunction(id) {
event.preventDefault(); // prevent form submit
var form = event.target.form; // storing the form
swal({
title: "Are you sure?",
text: "But you will still be able to retrieve this file.",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, Delete it!",
cancelButtonText: "No, cancel please!",
closeOnConfirm: false,
closeOnCancel: false
},
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
// so you can get the data from $_POST variables, says $_POST['delete'] $_POST['v_id']
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
}
});
swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
And this is my archive query . Don't bother about my query I set the status to 0 for me to archive one data and it will go to archive page. I just want to display the SWEET ALERT when I'm deleting the data or archiving it. Thanks in advance.
<?php session_start();
if(empty($_SESSION['id'])):
header('Location:../index');
endif;
include("../dist/includes/dbcon.php");
$id=$_REQUEST['id'];
$result=mysqli_query($con,"UPDATE accounts_at SET status = 0 WHERE id ='$id'")
or die(mysqli_error());
if ($result !== false) {
echo "<script type='text/javascript'>alert('Successfully deleted a account!');</script>";
echo "<script>document.location='index'</script>";
}
?>
Your UPDATED alert is in the wrong spot if you want it to run after the object is officially deleted on the server.
function(isConfirm){
if (isConfirm) {
// this is `post` request to the server
$.ajax({
method: 'POST',
data: {'delete': true, 'id' : id },
url: 'user_del.php',
success: function(data) {
//if you put it here it will run after the file is deleted
swal("Updated!", "Your imaginary file has been Deleted.", "success");
}
})
//if you put it here it will run before and even if your file is not deleted
// swal("Updated!", "Your imaginary file has been Deleted.", "success");
} else {
swal("Cancelled", "Your file is safe :)", "error");
}
Open up the develop console in your web browser. Does it give you any errors?
Do you get any alerts at all?
try this:
function archiveFunction(id) {
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function (isConfirm) {
if (!isConfirm) return;
$.ajax({
url: "delete.php",
type: "POST",
data: {
id: id
},
dataType: "html",
success: function () {
swal("Done!", "It was succesfully deleted!", "success");
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Error deleting!", "Please try again", "error");
}
});
});
}
I use Ajax and SweetAlert2 library to use alert UI. I search the how can I show the loading process during get data from server and I thought I can use beforeSend function. I write code like this.
So I put the Loading Process code inside the beforeSend but I don't know why It's not working. So I want to check is it works in beforeSend code so I write console.log code inside it and it actually works. But I don't know why the Swal.showLoading(); code is not working.
When I just type it in google console it works.
Loading Code is Simple.
Swal.showLoading();
And I want When it finish it show Finish Code.
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!'
}).then((result) => {
if (result.value) {
$.ajax({
type: "POST",
// contentType: "application/json",
url: `/${userId}/admin/getData`,
dataType: "json",
beforeSend: function () {
Swal.showLoading();
console.log('Loading');
},
success: function (redrawData) {
console.log(JSON.stringify(redrawData));
let existTable = $('#dataTable').DataTable();
existTable.destroy();
$('#dataTable').DataTable({
aaData: redrawData, // Returned Data from Server
aoColumns: [{
mData: 'id',
"render": function (value, type, row) {
return `${row.id}`;
}
},
{
mData: 'name'
},
{
mData: 'type'
},
{
mData: 'url'
},
{
mData: 'imgurl',
"render": function (value, type, row) {
return `<img src="${row.imgurl}">`;
}
},
{
mData: 'sumlang'
},
{
mData: 'pjdate1'
},
{
mData: 'pjdate2'
},
{
mData: 'githuburl'
}
]
})
},
complete: function () {
Swal.fire(
'Get!',
'Your file has been deleted.',
'success'
)
},
error: function (e) {
Swal.fire(
'Failed to save',
'If this message is output continuously, please contact to administrator.',
'error'
)
}
});
}
})
}
I never used SweetAlert but I have taken a look on their website exmaple and found this
const ipAPI = 'https://api.ipify.org?format=json'
Swal.queue([{
title: 'Your public IP',
confirmButtonText: 'Show my public IP',
text:
'Your public IP will be received ' +
'via AJAX request',
showLoaderOnConfirm: true,
preConfirm: () => {
return fetch(ipAPI)
.then(response => response.json())
.then(data => Swal.insertQueueStep(data.ip))
.catch(() => {
Swal.insertQueueStep({
type: 'error',
title: 'Unable to get your public IP'
})
})
}
}])
They use fetch with preConfirm in their exmaple, but in your case, I guess you can try to use preConfirm attribute that return the Promise created by the JQuery $.ajax() function
Example:
/* Mypage */
function getData() {
Swal.fire({
title: 'Do you want to get data from Github?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, Get DATA!',
showLoaderOnConfirm: true,
allowOutsideClick: () => !Swal.isLoading(),
preConfirm: function(){
return $.ajax(...); //Your ajax function here
}
});
}
You could just set the showLoaderOnConfirm to true to show the preloader when you click the continue button. Then, add the ajax call inside the preConfirm. Just make sure to return the response and catch any errors.
Swal.fire({
title: 'Submit your Github username',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: 'Look up',
showLoaderOnConfirm: true,
preConfirm: (login) => {
return fetch(`//api.github.com/users/${login}`)
.then(response => {
if (!response.ok) {
throw new Error(response.statusText)
}
return response.json()
})
.catch(error => {
Swal.showValidationMessage(
`Request failed: ${error}`
)
})
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.value) {
Swal.fire({
title: `${result.value.login}'s avatar`,
imageUrl: result.value.avatar_url
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#8"></script>
I was able to send data when the confirm button pressed.
however, when the cancel button pressed sweetalert2 shows as it successfully inserted the data.
back-end shows as it a empty string.(in the database table)
how to validate when I pressed the cancel button, not to send data to the back-end.
Javascript function
function inputPass(complaintID) { // complaint id pass is ok.
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(sample_text) {
console.log(sample_text);
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: sample_text}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
}
});
}
php ajax code
function complaint_answered() {
include_once('../backend/ConsumerComplaint.php');
$con_complaint = new ConsumerComplaint();
$res = $con_complaint>mark_as_answered($_POST['complaintID'],$_POST['sampleText']);
echo $res;
}
This is my class function
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment['value']; // $comment is a associative array, with the key of 'value'
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
image of when i pressed cancel button in network panel in chrome
image of the console
image of the post data in chrome
I'm new to development and can't get around how to solve this issue.
please can anyone give me what I'm doing wrong here.
Thnks!
You only get the result.value if the user clicked on Ok so you can check if there is a value and if it is empty you show your error message. If there is no value nothing happens.
Snippet:
swal({
text: 'Input comment message',
input: 'textarea',
showCancelButton: true,
}).then(function(result) {
if(result.value) {
$.ajax({
type: "POST",
url: "../ajax/ajax_active_deact.php?type=complaint_answered",
data: {complaintID: complaintID, sampleText: result.value}
}).done(function (res) {
if(!res) {
swal({
type: 'error',
html: 'insert the valid text'
});
} else {
swal({
title: 'done',
text: 'all right',
type: 'success',
allowOutsideClick: false,
confirmButtonText: 'Ok'
});
}
});
} else if (result.value === "") {
swal({
type: 'warning',
html: 'cannot proceed without input'
});
}
});
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#7.28.7/dist/sweetalert2.all.min.js"></script>
Your Class:
In your php ajax code you are passing the $_POST['sampleText'] which is not an array but a string so $comment['value'] will not contain the text.
function mark_as_answered($id, $comment) {
//var_dump($comment);
$val = $comment;
$sql = "UPDATE c_consumer_complaint SET `status` = 'answered', `update` = '$val'
WHERE complaint_id = '$id' ";
$res = $this->conn->query($sql);
return $res;
}
PS: Please educate yourself on SQL-Injection so people cant inject harmful code into your SQL-Queries.
Looks like sample text is always set to an array. I would try changing the if statement
if(sample_text === '') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
to something like
if(sample_text['dismiss'] == 'cancel') { // problem is here.
swal({
type: 'warning',
html: 'cannot proceed without input'
});
} else {
console.log(sample_text);
I'm scratching my head for a couple of days now and I can't get SweetAlert2 to do a AJAX call and return "Success" if it succeeded or show me an error in the same box if something goes wrong, leaving the user free to try again.
My implementation is following so far. The problem is that it shows the error in the box, but closes it at the same time:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve,reject) {
$.ajax({
url: '*****', // Invalid URL on purpose
type: 'POST',
data: {test: true}
})
.done(function(data) {
resolve(data)
})
.fail(function() {
reject()
});
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
title: `Success`,
text: result.value
})
}
}).catch((result) => {
swal.showValidationError('POST failed. Please try again.');
})
In the documentation I cannot find a AJAX call with a showValidationError. The closest I found is a fetch() call, but those are only for GET, as far as I know.
I also tried something like: return true, return false, throw new Error, promises inside promises, but that was all trial-and-error, so I came here.
I also made a fiddle: https://jsfiddle.net/xpvt214o/306267/
Thanks in advance for any help and/or suggestions.
After one more day I figured it out. I had to .then and .catch the $.ajax and attach swal.showValidationError on it in order to work.
On a AJAX error it will show following in the same box now (The user can try as many times as he pleases):
On success following:
swal({
title: 'Submit?',
text: 'Are those informations correct?',
type: 'question',
showCancelButton: true,
confirmButtonText: 'Absolutely',
cancelButtonText: 'Not sure',
showLoaderOnConfirm: true,
preConfirm: () => {
return $.ajax({
url: '***',
type: 'POST',
data: 'test'
})
.then(response => {
return response
})
.catch(error => {
//console.log(error); // Nice to view which properties 'error' has
swal.showValidationError(
`An error ocurred: ${error.status}`
)
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
type: 'success',
title: 'Success',
text: result.value
})
}
})
Fiddle: https://jsfiddle.net/z3kfhsj8/6/