Sweetalert2 redirect on confirm - sweetalert2

When the user clicks the confirm button in SweetAlert2 I'd like to redirect the user to another page and keep the modal open to show that the redirect is in progress.
I've managed to achieve using by re-initialising the modal after it closes and toggling the loading state. Is there a nicer built-in way? It was possible in the old v1.
var redirect = function () {
return Swal.fire({
type: 'warning',
title: 'Are you sure?',
confirmButtonText: 'Yes',
showLoaderOnConfirm: true,
allowOutsideClick: false,
preConfirm: function () {
window.location.href = 'https://dapurlindawaty.com';
}
});
};
redirect().then(function (result) {
if (result.value) {
redirect();
Swal.showLoading();
}
});
https://jsfiddle.net/bytestream/vfzgx10L/2/

Related

Sweet alert 2 Okay go to new page cancel stay at the page how?

Hi i got some problem with my sweet alert where i have redirected the user when click okay it be sent to the new page but if cancel they remain at the same page and close the alert boxhow can i do it ?
Here my code for the sweet alert
Swal.fire({
icon: 'success',
title: 'Insert Successfully!',
html: 'The information have inserted successfully!<br>By pressing <b>okay</b> this page will go to <b>manage user</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
confirmButtonText: 'Okay',
cancelButtonColor: '#d33',
confirmButtonColor: 'btn-success',
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(Okay => {
window.location.href = 'manageUsers_api.html';
})
Hi i have fix it by creating a if and else if with a value confirm
.then(function(inputvalue){
if(inputvalue.isConfirmed){
window.location.href = 'manageUsers_api.html';
} else if(inputvalue.isCancel){
Swal.fire('')
}
})

Handling AJAX return values in SweetAlert2

I use a SweetAlert2 Popup with an AJAX request. Once the user clicks on submit I execute the request.
In the PHP file I then make some validation on the submitted data and depending on the result I want to give a feedback in SweetAlert2 for the user as information.
Here is my SweetAlert2 Code:
$('#sweet-ajax').click(function () {
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Yes, submit!",
cancelButtonText: "Cancel",
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger m-l-10',
preConfirm: function(givenData){
return new Promise(function(resolve, reject) {
setTimeout(function(){
//if statment only for test purposes filled with 2==1
if(2 == 1){
swal("Oops", "Sorry something strange happend!", "error")
}else{
resolve()
}
}, 2000)
})
},
allowOutsideClick: false
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
})
swal({
//only if the response from the AJAX is correct - but how?
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' //need to get the return value of the AJAX request and append it here
})
}, function(dismiss) {
if (dismiss === 'cancel') {
swal(
'Cancelled',
'The action have been cancelled by the user :-)',
'error'
)
}
})
});
And the checkTool.php file:
<?php
$registration = $_POST['registration'];
$ammountInput= $_POST['ammount'];
$email= $_POST['email'];
//only some demo things here. Implement it after the SweetAlert2 stuff works properly
if ($registration == "success"){
return response(json_encode(array("abc"=>'Success')));
}else{
return response(json_encode(array("abc"=>'Error')));
}
?>
How can I now determinate what is the response from the AJAX request in the Javascript Code of SweetAlert2?
Is it possible to handle the AJAX response in SweetAlert2?
Wrap your sweet alert inside the ajax .done(function(response){}) function
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
}).done(function(response) {
if(response['abc'] === 'Success') {
swal({
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' + response['answer']
})
}
});
})
}, function(dismiss) {
In my experience what made it work, keeping in mind the use of showLoaderOnConfirm: true is doing the ajax call inside the preconfirm, and getting from the json response the elements I need as follows:
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning"
showLoaderOnConfirm: true,
preConfirm: function () {
return new Promise(function (resolve) {
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(objectToPost),
url: "/assets/php/checkTool.php",
dataType: 'json', // in ,my case the absence of this was the cause of failure
})
// in case of successfully understood ajax response
.done(function (myAjaxJsonResponse) {
console.log(myAjaxJsonResponse);
swal(
"My title!",
"My response element is: " + myAjaxJsonResponse.selectedElement,
"success"
);
})
.fail(function (erordata) {
console.log(erordata);
swal('cancelled!', 'The action have been cancelled by the user :-)', 'error');
})
})
},
})
.catch(swal.noop)
The swal being invoked when clicking a button, on my scenario.I hope this helps someone, as it took me quite some time to make it work.

How to open a modal in Drupal 8 without using a link?

The modal isn't triggered by a link on the page which the user has clicked. The modal is triggered when the user arrives on the url.
Think of something like a disclaimer that pops up as soon as the user arrives on the url.
You can use the Drupal.dialog function for this.
For example:
var $myDialog = $('<div>My dialog text</div>').appendTo('body');
Drupal.dialog($myDialog, {
title: 'A title',
buttons: [{
text: 'Close',
click: function() {
$(this).dialog('close');
}
}]
}).showModal();
See node.preview.js for another example.
Update: To use this with an AJAX request/response:
Drupal.ajax({
url: 'some/path',
success: function(response) {
var $myDialog = $('<div>' + response.data + '</div>').appendTo('body');
Drupal.dialog($myDialog, {title: 'Some title'}).showModal();
}
}).execute();

Displaying a message in a dialog box using AJAX, jQuery, and CakePHP

I have a form, and when users submit this form, it should pass the data along to a function using AJAX. Then, the result of that is displayed to the user in a dialog box. I'm using CakePHP (1.3) and jQuery to try and accomplish this but I feel like I'm running into the ground.
The form will eventually be used for uploading images with tags, but for now I just want to see a message pop up in the box..
The form:
<?php
echo $this->Form->create('Image', array('type' => 'file', 'controller' => 'images',
'action' => 'upload', 'method' => 'post'));
echo $this->Form->input('Wallpaper', array('type' => 'file'));
echo $this->Form->input('Tags');
echo $this->Form->end('Upload!');
?>
The AJAX:
$(document).ready(function() {
$("#ImageUploadForm").submit(function() {
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
$("#dialog-modal").dialog({
$("#dialog-modal").append("<p>"+html+"</p>");
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
})
}
});
return false;
});
});
NOTE: if I put $("#dialog-modal").dialog({ height: 140, modal: true }); OUTSIDE of the $.ajax but inside the $("#ImageUploadForm").submit(function() { and comment out the $.ajax stuff, I WILL see a dialog box pop up and then I have to click it for it to go away. After this, it will not forward to the location /images/upload/
The method that AJAX calls:
public function upload()
{
$this->autoRender = false;
if ($this->RequestHandler->isAjax())
{
echo 'Hi!';
exit();
}
}
$this->RequestHandler->isAjax() seems to do either absolutely nothing, or it is always returning false. I have never entered an if statement with that as the condition.
Thanks for all the help, if you need more information let me know.
Try this:
$(document).ready(function(){
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
//First you must append to div:
$("#dialog-modal").append("<p>"+html+"</p>");
$("#dialog-modal").dialog({
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
}); //dialog
}//success
});//ajax
Note the first sentence:
$("#dialog-modal").append("<p>"+html+"</p>");
it can not be a propertie. You must pass an object as a parameter to dialog() function so properties or member of an object looks like:
{
height:140,
buttons:{},
anotherPropertie: 'value'
}
If you call to dialog() function after ajax(), the dialog will be empty because will execute before success() function declared inside ajax().

MVC 3 Client side validation on jQuery dialog

I am showing lots of form using jquery dialog and I wish to add in client side validation on it. I read through some examples, saying that mvc 3 already somehow support jquery client side validation, but I tried by including the necessary script, and my form like this:
#using (Html.BeginForm("CreateFood", "Home", FormMethod.Post, new { id = "formData" }))
{
#Html.ValidationSummary(false, "Please fix these errors.")
When i try to submit my form without fill in the required field, I still dint get any message. Can anyone give me more idea / explanation / examples on this??
Really needs help here... Thanks...
UPDATE (add in the script for my dialog)
$createdialog.dialog("option", "buttons", {
"Cancel": function () {
//alert('Cancel');
$createdialog.dialog('close');
},
"Submit": function () {
var frm = $('#formData');
$.ajax({
url: '/Food/CreateFood',
type: 'POST',
data: frm.serialize(),
success: $createdialog.dialog('close')
});
}
});
Once dropped, open dialog:
// Once drop, open dialog to create food
options.drop = function (event, ui) {
// Get the ContainerImgName which food dropped at
var cimg = $(this).attr('id');
// Pass in ContainerImgName to retrieve respective ContainerID
// Once success, set the container hidden field value in the FoodForm
$.ajax({
url: '/food/getcontainerid',
type: 'GET',
data: { cImg: cimg },
success: function (result) { $('#containerID').val(result); }
});
clear();
$.validator.unobtrusive.parse($createdialog);
$createdialog.dialog('open');
};
I've faced the same problem, solved with:
$(name).dialog({
autoOpen: true,
width: options.witdth,
heigth: options.height,
resizable: true,
draggable: true,
title: options.title,
modal: true,
open: function (event, ui) {
// Enable validation for unobtrusive stuffs
$(this).load(options.url, function () {
var $jQval = $.validator;
$jQval.unobtrusive.parse($(this));
});
}
});
of course you can add the validation on the close event of the dialog, depends on what you're doing, in my case the popup was just for displaying errors so I've performed validation on load of the content. (this pop up is displaying am Action result)
For every dynamically generated form you need to manually run the validator once you inject this content into the DOM as shown in this blog post using the $.validator.unobtrusive.parse function.

Resources