JQuery UI Dialog and duplicated form elements - javascript

I am using a JQuery UI Dialog and the ajax submit plugin from malsup.com.
The issue is that the UI Dialog (I believe that is the culprit) is duplicating the fields of the form. It would not be such an issue except that this form is for uploading multiple files. The form uses a DataTable.
Apart from the duplicating fields the process is fine.
I am not re-using the dialog, which would duplicate the fields (see this )
The page gets the form and submits it through ajax: here is the code:
function smxTableDialogForm ( aURL, tableId, row ) {
var lData = "";
var lURL = aURL.split("?");
var lDialog;
if (lURL.length == 2){
lData = lURL[1];
lURL = lURL[0]
};
$.ajax({
type: "POST",
url: lURL,
data: lData,
dataType: "json"
}).
done( function(response){
if ( response.success ){
lDialog = $("<div></div>").dialog( {
height: "auto",
maxHeight: 800,
width: 750,
autoOpen: false,
buttons: [
{ text: "Save",
icons: {primary: "ui-icon-check" },
click: function () {
smxAjaxSubmit(response.formid);
$(this).dialog("close");
}
},
{ text: "Cancel",
icons: {primary: "ui-icon-close"},
click: function() {
$(this).dialog("close");
}
}],
close: function (event, ui) {
$(this).remove();
},
resizable: false,
modal: true
});
lDialog.html(response.content);
lDialog.dialog("open");
}
else {
$.alert(response.message, response.title);
};
}).
fail( function(jqXHR, textStatus, errorThrown) {
$.alert("Sorry, no info to display.", "oops");
});
};
function smxAjaxSubmit (aFormId) {
$("#" + aFormId).ajaxSubmit({
dataType: "json",
beforeSend: function(){
$.blockUI({ message: '<h3><img src="/sysimages/ajaxloader.gif" /> Just a moment...</hr>' });
},
complete: function(){
$.unblockUI();
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
$.alert("Problem. status: " + textStatus + "; error: " + errorThrown, "oops");
}
});
};
Any ideas gratefully received. Thanks.

Related

Laravel Hiding Validation Errors Message with Ajax when is true

i have implement the validation errors message with ajax successfully, but when the previous input form is true, the previous error in that input form is not hiding. Anyone can help me to hide the previous error if input form is true?
This is my javascript code :
$.ajax({
url: `${window.url}/income`,
type: "POST",
data: {
_token: CSRF_TOKEN,
detail: arrValues,
data_contact_id,
total,
description,
invoice,
transaction_date,
to_account_id,
},
dataType: "JSON",
success: function (response) {
console.log(response);
if (response.status) {
Swal.fire({
icon: "success",
type: "success",
title: response.message,
showConfirmButton: true,
}).then((result) => {
window.location.href = `${window.url}/income`;
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
let fields = [
"data_contact_id",
"invoice",
"transaction_date",
"to_account_id",
"description",
];
fields.map((field) => {
$(`#${field}`).removeClass("is-invalid");
$(`.${field}-error`).html(``);
});
let errors = jqXHR.responseJSON.errors;
$.each(errors, function (key, value) {
$(`#${key}`).addClass("is-invalid");
$(`.${key}-error`).append(`
<span class="text-danger" style="font-size: 0.8rem">
${value.map((v) => "<strong>" + v + "</strong><br>")}
</span>
`);
console.log("Field : ", key);
});
Swal.fire({
icon: "error",
type: "error",
title: "Error!",
showConfirmButton: true,
});
},
});
In my controller i have return validation error json from Validator::make()
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()]);
}
$.ajax({
beforeSend: function(){
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();
},
complete: function(){
// Handle the complete event
}
error : function(){
// Handle the error event
}
// ......
});
$(`#${key}`) add class key_of_form
$(`.${key}-error`) add class error_of_key
before submit of form or beforeSend of ajax you need reset error messages same as :
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();

How can I implement a wait mechanism until receiving confirm dialog response?

Here is my code:
$(function () {
$(document).on('click', '.fa-times', function(e){
e.stopPropagation();
var result = ConfirmDialog('Are you sure?');
if (result) {return false}
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
})
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>'+message+'?</h6></div>')
.dialog({
modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
})
But my code run that ajax request without waiting for the response of ConfirmDialog(message) function. How can I force it to wait?
You have 2 functions which get triggered depending on which confirm button is selected. Handle your ajax code from there.
I liked how Abhijit's answer abstracted out the code, but I think he missed something.
$(function() {
$(document).on('click', '.fa-times', function(e) {
e.stopPropagation();
function getConfirmHandler(element){
return function handleConfirm(result) {
if (result) {
return false
}
var row = element.closest('tr');
row.css('opacity', '0.3');
var word = element.closest('td').siblings('.word').text();
$.ajax({
url: '../../te_addStopWord',
type: 'GET',
data: {
word: word
},
dataType: 'JSON',
success: function() {
row.remove();
}, // success
error: function($a, $b, $c) {
alert($b);
row.css('opacity', '1');
}
}); // ajax
}
}
ConfirmDialog('Are you sure?', getConfirmHandler($(this)))
});
function ConfirmDialog(message, callback) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
$(this).remove();
callback(true);
},
No: function() {
$(this).remove();
callback(false);
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
})
Try move ajax into your ConfirmDialog:yesfunction. Or Try to use promise.
buttons: {
Yes: function () {
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},

Jquery-ui open dialog from js loop

I'm developing a web site with JQuery
I have encountered the following problem:
Going through an array in a loop, and every value is sent to a function that sends it to the server by Ajax.
On success a message is generated in JQuery- Dialog, in which buttons and button- functions are adjusted by the values returned from the server.
The problem is, that the JQuery-dialog is only triggered at the end of the loop, so I cannot tell which message refers to what value.
The loop func:
$('#List').find('option').map(function () {
semelO= $(this).val();
**getData**("Insert_hashala", "Inserthashala", false, "***setAlert***", false, "inserthasala", ["semelO", semelO], null, "RefershLendGrid", null);
});
The function signature:
function **getData**(procAlias, funcName, empytFields, ***onSuccessEvent***, isAsync, dataGroup, moreValues, onFailure, setDisplay, onFailureEvent)
The Ajax
jQuery.ajax({
type: "POST",
contentType: 'application/json',
dataType: "json",
url: "SvcSifria.asmx/" + funcName,
data: dataJsonString,
success: function (data) {
if (onSuccessEvent != undefined) eval(***onSuccessEvent*** + '(data)');
if (setDisplay != undefined) eval(setDisplay + '(data)');
},
async: isAsync
});
}
The Dialog function:
function ***setAlert***(data, error) {
myJson = jQuery.parseJSON(data.d);
text = data.d;
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-mess").dialog({
autoOpen: false,
modal: true, appendToBody: true,
buttons: [{
text: textButton,
id: "cancle",
click: function () {
$(this).dialog("close");
},text: textButton,
id: "ok",
click: function () {
getData("Insert_hashala", "Inserthashala", false, "setAlert", isAsync, "inserthasala", [returnValue, "true", "sumHashala", sumHashala, "semelOtek", semelOtek], null, "RefershLendGrid");
$(this).dialog("close");
}
}]
});
$("#ok").focus();
$("#dialog-mess").dialog("open");
}

Trigger a java script in before submit form

Hello while creating my php script I came across a difficulty to execute script 1[ajax uploader] ( on from submit ). The code that triggers the upload is uploadObj.startUpload(); i tried to add it on script 2 in before submit action, but somehow it doesn't lunch. Can you help me?
Script 1.
var uploadObj = $("#mulitplefileuploader").uploadFile({
url: "uploader/upload.php",
multiple: false,
fileName: "myfile",
maxFileSize: 655360 * 100, //5mb
allowedTypes: "jpg,png,gif,zip,txt,doc,docx,csv,xml,pdf,JPG,JPEG,jpeg",
maxFileCount: 1,
autoSubmit: false,
dragDropStr: "<span><b>Przeciągnij i upuść plik</b></span>",
abortStr: "Anuluj",
cancelStr: "Przerwij",
doneStr: "Dodano",
dynamicFormData: function () {
var data = {
uid: "<?PHP echo $_SESSION['userid']; ?>"
}
return data;
},
onSubmit: function (files) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Submitting:" + JSON.stringify(files));
},
onSuccess: function (files, data, xhr) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Success for: " + JSON.stringify(data));
},
afterUploadAll: function () {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>All files are uploaded");
},
onError: function (files, status, errMsg) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Error for: " + JSON.stringify(files));
}
});
Script 2.
$(document).ready(function () {
var options = {
target: "#msgholder",
beforeSubmit: function () {
showLoader;
},
success: showResponse,
url: "ajax/controller.php",
resetForm: 0,
clearForm: 0,
data: {
processTicket: 1
}
};
$("#admin_form").ajaxForm(options);
});
function showResponse(msg) {
hideLoader();
$(this).html(msg);
$("html, body").animate({
scrollTop: 0
}, 600);
}

How do I change where the alert message is displayed on the screen?

The alert message is the following:
if (allInputValid) {
var bC = parseInt(document.getElementById("BCutId").value);
if(bC>0){
$.ajax({
url: BrowserSide.Url.getFullUrl('C/Edit'),
type: 'Post',
data: $(CForm).serialize(),
success: function (result) {
$('#CId').val(result.cId);
if (result.type == "created") {
BrowserSide.C.PopupMsg("created successfully!!");
}
else {
BrowserSide.C.PopupMsg("modified successfully!!");
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
BrowserSide.AjaxLog.HandleAjaxCallFail(XMLHttpRequest, textStatus, errorThrown, "ajax error in in C.js clickSubmitBt");
}
});
} else {
BrowerSide.C.PopupMsg("Please select bC!");
}
}
return false;
However, the alerts is standardized to pop up center in the screen. I want the pop up/alert to pop up on the center left of the screen. How do I do that?
I'm using ASP.NET MVC 4
EDIT:
I have this functions that's supposed to change the window to appear on the left but it still appears centered. Why?
PopupMsg: function (msg) {
var browser = BrowserSide.BrowserCompatibility.GetBrowser();
if (browser.toLowerCase().indexOf("explorer") != -1) {
//alert(msg);
$("#CasePopupDialog").html(msg);
$("#CasePopupDialog").dialog(
{
dialogClass: "no-close",
modal: true,
title: 'Message Window',
//show: 'slide',
//hide: 'slide',
width: '315px',
height: 'auto',
//resizable: true,
closeOnEscape: true,
focus: true,
position: ['left',100],
buttons: {
Ok: function () {
$("#CasePopupDialog").html("");
$(this).dialog("close");
}
},
});
} else {
alert(msg);
}
},

Categories

Resources