jQuery fileDownload conflicting with another jQuery plugin - javascript

I have two different jquery plugins loaded, one is UI related which allows me to display message popups and the other is the ajax fileDownload plugin. They both work fine. However, when I seem to run one function, it then starts conflicting with the other function.
I have a function called Export which initiates the fileDownload ajax request when a button is clicked. But then after the fileDownload is over, if I click on the button that launches the ExitAlert function, I end up getting the fileDownload re-initialising with the exit message. Below are the two functions.
Any idea what is going wrong?
Thanks
function Export() {
$("#Form").submit(function (e) {
e.preventDefault();
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
});
}
function ExitAlert() {
$("#Form").submit(function (e) {
e.preventDefault();
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
});
}

I seemed to have got it to work by changing the e.preventDefault and the functions now look like this (seems to work now):
function Export() {
$("form").submit(function (e) {
e.preventDefault();
});
$.fileDownload('export.php?'+ Math.random(), {
httpMethod: 'POST',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $('#Form').serialize(),
successCallback: function (url) {
$("#ExportButton").prop("disabled", true);
$(pleaseWait).remove();
},
failCallback: function (responseHtml, url) {
$(pleaseWait).remove();
}
});
}
function ExitAlert() {
$("form").submit(function (e) {
e.preventDefault();
});
$.msgBox({
title: "Are You Sure?",
content: "<font size=2><b>Exit without saving? </b><br><br>All changes will be lost!</font>",
opacity:0.8,
type: "confirm",
buttons: [{ value: "Yes" }, { value: "No" }],
success: function (result) {
if (result == "Yes") {
document.Form.submit();
}
}
});
}

Related

Set isConfirmed to true after timer runs out on SweetAlert2

I am using sweetalert2 when confirming an input from user. I am using a dialog with two buttons , confirm button and cancel button, also I added a timer. When submit button is clicked everything works fine ( ajax is called ) but when timer runs out I want the same result as confirm button. I have tried adding Swal.isConfirmed = true, result=true but didn't get desired one.
Swal.fire({
title: 'Дали сакате да ги зачувате промените?',
showDenyButton: true,
confirmButtonText: 'Зачувај',
confirmButtonColor: '#00CA4E',
denyButtonText: `Откажи`,
denyButtonColor: '#FF605C',
html: '<strong></strong> секунди.<br/>',
timer: 3000,
didOpen: () => {
timerInterval = setInterval(() => {
Swal.getHtmlContainer().querySelector('strong')
.textContent = (Swal.getTimerLeft() / 1000)
.toFixed(0)
}, 100)
},
willClose: () => {
clearInterval(timerInterval);
Swal.isConfirmed = true;
}
}).then((result) => {
/* Read more about isConfirmed, isDenied below */
if (result.isConfirmed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("SubstitutionAddPlayers","Scoreboard")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
} else if (result.isDenied) {
//Swal.fire('Changes are not saved', '', 'info')
}
})
I want when timer runs out, result in then to be true and ajax call to be executed.
If a SWAL2 is dismissed from a timer, you can use result.isDismissed the same way as result.isConfirmed in any conditional statement.
if (result.isDismissed) {
// .. code if timer is dismissed
}
if (result.isConfirmed) {
// .. code if timer is confirmed
}
This is the result response if you remove all buttons and let it be:
{isConfirmed: false, isDenied: false, isDismissed: true, dismiss: 'timer'}
So try adding
if (result.isDismissed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("
SubstitutionAddPlayers ","
Scoreboard ")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
}
Note: Consider disabling outside click on that specific one maybe.

Validation DropDownList outside grid

I have kendo dropdownlist and button submit. I want if the user not select anything in dropdown(position), there will be validation that inform the user must select one position at least at dropdown. Then, if the user has click the position, so the user can submit the data. I have used some method like "required" but not working.
HTML
<input id="dropdown" style="width:200px;" />
JavaScript for kendoDropDownList (position)
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "./testjson.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: function(e){
console.log(this.value());
// $('#AccountingTree').data('kendoTreeView').homogeneous.read();
homogeneous1.read();
homogeneous2.read();
homogeneous3.read();
homogeneous4.read();
homogeneous5.read();
homogeneous6.read();
homogeneous7.read();
homogeneous8.read();
homogeneous9.read();
homogeneous10.read();
homogeneous11.read();
homogeneous12.read();
homogeneous13.read();
homogeneous14.read();
}
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
For dropdownlist above, i"m using homogeneous data (treeview).
Anyone have any idea or reference on this question?
JavaScript AJAX call for submit button
//AJAX call for button
$("#primaryTextButton").click(function(){
if($("#dropdown").data("kendoDropDownList").value() == ""){
kendo.alert("Please select position.");
}
});
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS")
{
kendo.alert("Data saved");
}else
{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
});
When you click the button, just get the value of the kendoDropDownList and do a
conditional statement. Hope this helps. Happy Coding ;D
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").data("kendoDropDownList").value();
if(test == ""){
kendo.alert("Please select position.");
}
else{
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS"){
kendo.alert("Data saved");
}
else{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
}
});

Problem: pass some parameters in ajax call (post)

I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?
Here is my code at the moment
jQuery(document).ready(function () {
function ajaxCall(action, callback) {
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
},
success: function (response) {
if (response.error == true) {
alert(response.errors.join('\n'));
}
else if (response.status == "DONE") {
callback(false);
}
},
error: function (xhr) {
console.log("Error: ", JSON.stringify(xhr));
callback(true);
}
});
}
jQuery('#ajax_add').click(function (event) {
event.stopPropagation();
var id = jQuery('#id').val();
var price = jQuery('#price').val();
//I want to send two variables: id, price
ajaxCall("addData", function (error) {
if (error) {
alert("Error!.");
}
else {
alert("It's OK!");
}
});
});
});
The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.
I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks
You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :
function ajaxCall(action, params, callback) {
Then in the ajax call :
jQuery.ajax('/index.php', {
type: 'POST',
dataType: 'json',
data: $.extend(params, {
option: 'quotes',
view: 'request',
task: action,
format: 'raw',
tmpl: 'component'
}),
...
The call inside the event will be like :
ajaxCall("addData", {id: id, price: price}, function (error) {

How can i put ajax in confirm button?

Hi friends i am trying to put ajax url in confirm button to update something in Database.
So i do this in JavaScript Section
function freeze_account() {
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}
and this is code for update
$manager_id = $_POST['manager_id'];
$state = '0';
$update=runQuery("UPDATE `users` SET `userStatus` =:userS WHERE `userID`=:user_id");
$update->bindparam(":userS",$state);
$update->bindparam(":user_id",$manager_id);
$update->execute();
My problem is when i press confirm button ajax works and go to another page but nothing happen in database.
What is wrong in my code Or Maybe I miss something?
any help any idea i will be grateful
Best Regards
look how i solved my problem
Maybe one benefit of my code
Thanks for every one suggestions or helping me
function freeze_account() {
var pid = $('#manager_id').val();
bootbox.dialog({
message: "Are you sure you want to Freeze this account ?",
title: "<i class='glyphicon glyphicon-trash'></i> Freeze !",
buttons: {
success: {
label: "No",
className: "btn-success",
callback: function() {
$('.bootbox').modal('hide');
}
},
danger: {
label: "Freeze!",
className: "btn-danger",
callback: function() {
$.post('update_freeze.php', { 'pid':pid })
.done(function(response){
bootbox.alert(response);
location.reload();
})
.fail(function(){
bootbox.alert('Something Went Wrog ....');
})
}
}
}
});
}
You need to set up an event listener on your button. Firstly, ensure you have an ID on your button so we can grab it.
Now, we create the event listener:
$("#button").on("click", freeze_account());
And, now when you click the button the ajax call should go through successfully.
However, it will still redirect yo due to its default behaviour.
To override this, simply prevent the default event:
function freeze_account(event) {
event.preventDefault(); // stops the button redirecting
$.confirm({
title: 'Confirm!',
content: 'This dialog will automatically trigger \'cancel\' in 6 seconds if you don\'t respond.',
type: 'red',
typeAnimated: true,
boxWidth: '30%',
useBootstrap: false,
buttons: {
confirm: function() {
var manager_id = $('#manager_id').val();
$.ajax({
url: "update_freeze.php",
type: "POST",
data: {
'manager_id': manager_id
},
success: function() {
location.reload();
}
});
},
cancel: function() {}
}
});
}

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");
}

Categories

Resources