I need help for fill a textarea with data recived from query DB.
I have a dialog (Jquery) that contain another dialog and into this one, a textarea.
pseudocode:
<MODAL>
<modalB>
<TextArea>some data recibed</textarea>
</modalB>
<MODAL>
When I call a function that opens the the textarea return the result from a DB (as wished). The problem is when I close the and open it up again, because the textarea returns empty. When I do it a second time, it works fine again (the textarea returns DB data).
javascript code:
function detalleSeguimiento(idSeguimiento) {
var datos = {'idSeguimiento': idSeguimiento};
$.get("detalleSeguimientosCargar.php", datos, function(data){
$("#textAreaDetalleSeguimiento").html(data);
});
$('#modalDetalleSeguimiento').dialog({
width:750,
minHeight:400,
modal: true,
title: 'titulo',
resizable: false,
});
}
Thank you!
EDIT: Thanks CrisC for the solution!
You just need to wait for the data to return before creating the dialog:
function detalleSeguimiento(idSeguimiento) {
var datos = {'idSeguimiento': idSeguimiento};
$.get("detalleSeguimientosCargar.php", datos, function(data){
$("#textAreaDetalleSeguimiento").html(data);
$('#modalDetalleSeguimiento').dialog({width:750,
minHeight:400,
modal: true,
title: 'titulo',
resizable: false});
});
}
Just move the dialog inside the $.get callback.
use promises and use callback for retrieve data when data retrieve the function will be call
and one more option is create eventlistner for receive data like data is avalaible the event is fire
Related
I'm using https://sweetalert2.github.io/
I tried using one single sweet dialog, but due to the others I couldn't make it work, and i've seen examples with fetch, but I'm using ajax, I saw a example with nested dialogs but once again, with fetch. In the code I put there are 2 comments where I would like to handle the loading dialog.
This is my script:
$(document).on("submit", "#formNuevoEstudiante", function (event) {
event.preventDefault();
$("#btnSubmit").prop("disabled", true);
let ap_paterno = $("#ap_paterno").val();
let ap_materno = $("#ap_materno").val();
let nombre = $("#nombre").val();
let sexo = $("#sexo option:selected").val();
let no_control = $("#no_control").val();
let carrera = $("#carrera option:selected").val();
let semestre = $("#semestre option:selected").val();
let sexo2 = sexo == "F" ? "Femenino" : "Masculino";
let mensaje = `x`;
let mensaje2 = `x`;
//Here is where I wan't to integrate the loading dialog
$.ajax({
url: "utils/ajax/nuevo_estudiante.php",
method: "POST",
data: {
ap_paterno: ap_paterno,
ap_materno: ap_materno,
nombre: nombre,
sexo: sexo,
no_control: no_control,
carrera: carrera,
semestre: semestre,
},
success: function (resp) {
if (resp == "existe") {
Swal.fire({
title: "Ya se encuentra registrado",
text: "x",
icon: "warning",
confirmButtonText: "Aceptar",
confirmButtonColor: "#0275D8",
}).then(function () {
window.location.href = "index2.php";
});
} else if (resp == "error") {
Swal.fire({
title: "Error",
text: "x",
icon: "error",
confirmButtonText: "Aceptar",
confirmButtonColor: "#0275D8",
});
} else if (resp == "ok") {
//Here is where I wan't to close the loading dialog
Swal.fire({
title: "Registro exitoso",
html: "<pre>" + mensaje + "</pre>" + mensaje2,
icon: "success",
confirmButtonText: "Aceptar",
confirmButtonColor: "#0275D8",
}).then(function () {
window.location.href = "index2.php";
});
}
},
});
});
The example given in the SWAL2 website isn't very suited for your use as it creates an input form itself while you already have an HTML form that gets input from the user. A basic easy-to-implement solution would be to use the showLoading and hideLoading methods with what you already have. From the documentation :
Swal.showLoading(): Shows loader (spinner), this is useful with AJAX
requests.
By default the loader be shown instead of the "Confirm" button, but if
you want another button to be replaced with a loader, just pass it
like this: Swal.showLoading(Swal.getDenyButton())
Swal.hideLoading(): Hides loader and shows back the button which was
hidden by .showLoading()
Just after the event.preventDefault(); line, you can add a loading dialog that will just display a loading message:
Swal.fire({
title: "Loading...",
html: "Please wait a moment"
})
Swal.showLoading()
Then, at the beginning of the success callback of your ajax request, just before entering the if condition, simply add a Swal.hideLoading() to stop displaying the loading animation.
Why does hideLoading and showLoading work on an already displayed popup?
The reason is because SweetAlert2 kind of (it seems to work like that but I didn't confirm it) works using static methods which takes their execution to a "global" scope, meaning that when you call one of SweetAlert2 methods, it runs and stores data in the same place: the Swal class which is shared everywhere. (If you want to know more about static class, there are several articles you can read on the internet)
Disclaimer! Now, I didn't take a look at how Swal stores data, or how it handles everything, but for the sake of argument, let's say it stores inside static properties like currentTitle, isLoading (which dictates whether or not a loading animation should be added to the popup), and more. That is effectively one reason why there's only one popup displayed at a given time (although by definition, there should be only one displayed).
So, when you call Swal.fire(), it essentially updates the Swal class properties (setting the currentTitle to Hello for example). When you call it again, it updates it again and effectively overwrites the values set by the previous call of fire(), replacing them with new ones.
But, unlike fire() which completely overwrites every property for the currently displayed popup, hideLoading and showLoading methods only overwrite ONE property: isLoading (reminder: this is how we've postulated SweetAlert works, the implementation could be made otherwise but for simplicity's sake, we assume it's like that) and let the others as is. That is why, when you use fire(), a new popup is displayed, but when using hideLoading and showLoading, the current popup displayed is changed.
I have a button's onclick set to use the following function EditContact. This function sets up a jquery dialog, gets the data from the server and displays it. Everything works but I would like to get it to work a little better. Right now the empty dialog pops up for the time it takes the code to go and fetch the content from the server then the dialog populates with the content. My question is how can I get the dialog to not pop up until the content has been received.
function EditContact() {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false,
autoOpen: false,
open: function (event) {
var szAction = "Content url for this example";
$(this).load(szAction,
function (response, status, xhr) {
$('#editContactView').dialog('open');
return false;
});
}
});
$('#editContactView').dialog('open');
}
I think you should be able to essentially turn what you have inside out and and open the dialog on $().load() completion. Something like this might do it:
function editContact() {
var szAction = "Content url for this example";
$(this).load(szAction, function (response, status, xhr) {
$('#editContactView').dialog({
modal: true,
width: 'auto',
position: ['top', 'center'],
resizable: false
});
});
}
Edit:
Notice I removed the {autoOpen: false}. This will create it and open it in one shot after you receive the content.
You are calling .dialog('open') twice: in the end of the code and in the callback for the loading.
As JavaScript is asynchronous, it runs the line $('#editContactView').dialog('open'); in the end before the data is received.
Removing this line should solve the problem.
Im using html5 capacities to read image width and height before submitting...
Well, this is not happening exactly, it seems like the time needed for the functions:
reader.readAsDataURL();
reader.onload = function();
image.onload = function();
To read the file is way too much than the time my form is able to wait before sending the pic.
I can check that the beforeSubmit function is triggered, but the form is submitted before it finishes.
Another weird thing is that I have replaced the beforeSubmit function content with a simple return false sentence and the form is being submitted anyway.
Am I missing something regarding the beforeSubmit option in ajaxSubmit?
The beforeSubmit function has been minimized to a return false statement, here comes the submit (the form is inside a dialog(), may be this the clue?:
$('.block .imgpop').on("click",function()
{
type = $(this).attr('emimage');
currentype = type;
options =
{
type: 'POST',
target: '#uploadverbose',
beforeSend: beforeSubmit,
resetForm: true,
success: showResponse,
data: { type: $(this).attr('emimage'), tempname: $(this).attr('id'), maxsize: imgsizesW[$(this).attr('emimage')] },
dataType : "text"
};
$('#uploadbitch').dialog(
{
closeOnEscape: true,
width: 800,
modal: true
});
return false;
});
$(document).on("click","#MyUploadForm input[type=submit]", function(e, submit)
{
if (!submit) e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
$(document).on("submit","#MyUploadForm", function(e, submit)
{
e.preventDefault();
$('#MyUploadForm').ajaxSubmit(options);
});
If you try to handle onclick on submit button then it doesn't stop form from submitting.
It may bot be exactly the answer, but it works. I have place all the image testing in the input field with a "change" event and it works just fine for me. Precocity in the form submitting is still unsolved.
I'm opening a dialog using a .load function and then I want to grab the values from the fields in the dialog defining the variables outside the dialog function, but it returns undefined, so my question is, how do I define the variables outside the dialog function to use it inside it,
An example what I want to do.
First I request the dialog:
$( '#dialog-form' ).load('table_models/add_to_table.php',function(){
$( '#dialog-form' ).dialog('open');
});
Now I define the variables and the dialog popup:
$(function() {
var sku = $( "#sku" ),
fba_sku = $( "#fba_sku" ),
asin = $( "#asin" ),
$( "#dialog-form" ).dialog({
title: 'New Product',
autoOpen: false,
height: 'auto',
width: 'auto',
modal: true,
buttons: {
"Done": function() {
// I want to get the var sku, fba_sku, asin here
}
},
}
}
I hope you understand what I want to do, if not I will try to explain it better,
Thanks
EDIT
The .load function being requested from a button on page, then the dialog function is on external JS file, there I want to define first the var of the fields from the dialog form and reuse it for all functions on this page.
Try defining the function outside the object, like so:
var cb = function() { /* stuff with sku, fba_sku, asin */ };
$("#dialog-form").dialog({
...
buttons:{"Done":cb}
});
Your understanding of "'Now' I define [...]" may be flawed–it's unclear where the ready function is defined. .load is asynchronous and will complete at an arbitrary time in the future.
Get the element values in the "Done" function so they're filled with the most recent values.
I have a very simple scenario where I want to POST the form using JQuery's ajax() method but perform request some confirmation from the user before actually performing the post.
I have a JQuery UI dialog with localized buttons in place in case you wonder what all the code with buttons below is about.
This is my code so far:
var i18n_deleteButtons = {};
i18n_deleteButtons[i18n.dialogs_continue] = function () {
return true;
$(this).dialog('close');
};
i18n_deleteButtons[i18n.dialogs_cancel] = function () {
return false;
$(this).dialog('close');
};
$('#delete-dialog').dialog({
open: function () {
$(this).parents('.ui-dialog-buttonpane button:eq(1)').focus();
},
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons: i18n_deleteButtons
});
$("form#form_attachments").submit(function (event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $(this), url = $form.attr('action');
// build array of IDs to delete (from checked rows)
var jdata = { 'attachmentIdsToDelete': [] };
$('input:checked').each(function () {
jdata['attachmentIdsToDelete'].push($(this).val());
})
$.ajax({
beforeSend: function (request) {
// Return false if you don't want the form submit.
$('#delete-dialog').dialog('open');
},
url: url,
type: "POST",
dataType: "json",
data: jdata,
traditional: true,
success: function (msg) {
$('#msg').html(msg);
}
});
});
The dialog actually opens up fine but clicking at any of the buttons results in nothing happening. The post doesn't happen and the dialog does not close regardless of which button was clicked.
How can I make this work?
Why not move the actual ajax call from the submit handler and trigger it when pushing a button in the delete dialog?
You could store you ajax call in a separat function and pass this functions and the url as parameters to the confirmation routine.
[pseudo code]
function callAjax() {
...
}
function submitHandler() {
confirmDialog({callback:callAjax,param:you_url});
}
function confirmDialog(obj) {
$('#yes_btn').click(function() {
// call the callback
obj.callback(obj.param);
});
$('#no_btn').click(function() {
// just close the dialog
});
}
This way the confirmDialog don't have to know anything about the ajax call, it will just execute the callback with the given parameter when the user clicks ok.
Because the default jquery UI dialog is a bit cumbersome for regular use and trouble to configure in some custom scenarios I looked around and found this Easy Confirm plugin which is based upon jquery&jquery UI default stuff. It also allows for very simple internationalization.
https://github.com/wiggin/jQuery-Easy-Confirm-Dialog-plugin