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

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();

Related

Sweetalert2 redirect on confirm

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/

Selectors not working on ajax response

I'm using ajax to submit pages and return content blocks based on user action for an onboarding sequence.
If have a page which loads and get 1 content element, the user then clicks Yes or No, which loads the next content element into the same space (via ajax).
For some reason my selectors don't seem to be working on that ajax loaded html.
Here is my ajax function which gets the form:
$.ajax({
beforeSend: function() {
$("#loader").toggleClass('progress');
},
type: 'POST',
dataType: 'json',
data: data,
url: baseUrl+'welcome/user_confirmation_form',
complete: function( response ) {
$("#loader").toggleClass('progress');
},
success: function( response ) {
console.log(response);
$("div.welcome-page > .col").html(response.response);
},
error: function( response ) {
$("#next-steps").html(response.response);
}
});
I'm then trying to access the submit button (have tried doing it as a ahref and button type=submit but nothing seems to be selecting the event.
$('div.welcome-page').on('submit', "user_complete", function(e) {
e.preventDefault();
console.log('FOund form');
var user = $(this).serializeArray();
console.log(user);
});
If I view source, the ajax returned HTML is not even in the dom, but it is when viewing the UI normally.
I'm guessing this has something to do with it?
How can I select all the form data?
Any time I click on the button or ahref it just fires the same page again.
If user_complete is a class you are assigning on your submit button in your loaded html, then you are missing a .
$('div.welcome-page').on('submit', ".user_complete", function(e) {
But this will only work if you're using a submit action as this is listening for a submit event. Maybe you want to listen for a click event?
You need to bind the events to your handlers for your newly added HTML elements. Your original call to
$('div.welcome-page').on('submit' ...
Only bound the event handler for the elements that were on the page at that point in time.
You can put your handler into a function ...
var myHandler = function(e) {
e.preventDefault();
var user = $(this).serializeArray();
}
And then after you load the new HTML you need to bind the handler to the event. So, on success with the AJAX you would ...
success: function( response ) {
$("div.welcome-page > .col").html(response.response);
$('div.welcome-page').on('submit', "user_complete", myHandler);
},

Asp.net mvc Create pdf Async on button click

I have created an application server side that will create a pdf of a report when requested. Then the link of that report can then be sent back to the client.
My question is how do I hook this up to a button click event in my asp.net mvc website. So the scenario is:
User fills in a few boxes.
Clicks the generate report button.
A little loading feedback indicator is shown.
A request is sent to the server, the server then generates the PDF report and sends back a url link to the pdf that is being hosted on the server.
The pdf will then be shown in the users browser (maybe in a new window).
Is this possible and is there any examples around that show how to do it?
Thanks in advance
I've done something similar.
When the user clicks the button it send an ajax request to the server passing some data:
$.ajax({
type: 'POST',
dataType: 'json',
url: '<%=Url.Action("GenerateReport", "MyController")%>',
data: { Param1: $('#Param1').val() , Param2: $('#Param2').val() },
beforeSend: function(xhr) {
$.blockUI({ message: '<h1> printing ...</h1>', css: { border: 'none', padding: '15px', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', opacity: .5, color: '#fff'} });
},
success: function(result) {
if (result.Success) {
FetchPdfDocument('<%=Url.Action("GetPdfReport", "MyController", New With {.id = "/"})%>' + result.Guid);
}
else {
alert("Problems!");
}
},
complete: function() {
$.unblockUI();
},
error: function(req, status, error) {
alert(error);
}
});
The controller writes the document on the disk and sends back a guid which is the name of the PDF document.
This is the other bit of javascript which opens the file creating an IFRAME:
function FetchPdfDocument(UrlToPdf)
{
$('#ifPdfReport').remove();
$(document.body).append('<IFRAME id="ifPdfReport" style="display:none;">');
$('iframe#ifPdfReport').attr('src', UrlToPdf);
// $('#ifPdfReport').load(function () { });
}
I've used jQuery BlockUI as loading feedback indicator.
Hope it helps.

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.

How to get ajax request into a variable in sencha touch?

What I am trying to do is is get the information I have in my ajax request as the badgetext number
Here is where I am trying to do it. This seems simple, but I cant figure it out.
Ext.Ajax.request({
url: '../lib/messages.php',
success: function(response, opts) {
var badge_number = Ext.decode(response.responseText);
console.dir(badge_number);
},
failure: function(response, opts) {
console.log('server-side failure with status code');
}
});
var buttonsGroup1 = [{
text: 'Messages',
//badge_number variable from ajax request would go here. badgeText: '2',
handler: tapHandler
}];
Ah ok, I misread the question.
So the most straight forward way to put the badge text on the button is to create a closure.
var button = new Ext.Button({
text: 'Messages',
handler: tapHandler});
Ext.Ajax.request({
....
success: function(response, opts){
button.setBadge(Ext.decode(response.responseText));
}
...
});
This will cause the badge text to be updated when the AJAX call completes. You can then add the object to a Panel or Toolbar after the AJAX request code as you would have before.
If you absolutely have to have the badge text on the button before it is created, you will need to create the button group inside the success function and assign/add it to the appropriate container object.

Resources