Jquery-ui open dialog from js loop - javascript

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

Related

Preprocess before kendo ui upload

I want to pass some data(a guid) to the upload method of the kendoUpload so that the particular MVC Controller action method will receive that data. Each time the upload happens, I need to pass this data (guid).
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
The field is fileId. I can call the above code block in a click event of the upload button and it works but the Kendo UI styles are not applied to the upload button at the initialization.
$("#propertyAttachmentUpload").click(
function() {
var fileId = guid();
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
});
How can I initialize the fileId without loosing the Kendo UI styles.
Note: I cannot call guid() inside upload method since the upload method calls for each uploading chunk. For all the chunks the fileId should be same for a particular file.
I've resolved this problem using a global variable and setting that variable in the click event of the upload button,
var fileGuid = '';
$(document).on('click', '#propertyAttachmentUpload', function() {
fileGuid = "";
fileGuid = guid();
})
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileGuid };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});

Reinitialze onChange event for Bootstrap multiselect

I have a series of multiselect dropdown controls. The first one (users) causes the second one (userGroups) to update when one of its values is changed and the second one (userGroups) causes the third one (theaters) to update the contents of its list.
The onChange event for the first dropdown (users) is working fine. But, the second one (userGroups) onChange event is not firing when one of it's values is changed and thereby not updating the list of the third dropdown (theaters).
I know from having worked with Javascript, the onChange needs to be reinitiazed; but, I do not know how to do this with the Bootstrap multiselect. My code follows:
$('.users').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
var userName = $('.users').val();
if (userName != null) {
userName = userName.toString();
}
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
}
});
$('.userGroups').multiselect({
numberDisplayed: 1,
maxHeight: 400,
includeSelectAllOption: false,
enableCaseInsensitiveFiltering: true,
filterBehavior: 'both',
disableIfEmpty: true,
onChange: function (element, checked) {
javascript: console.log("OnChange event fired");
var groupId = $('.userGroups').val();
if (groupId != null) {
groupId = groupId.toString();
}
$.ajax({
url: '#Url.Action("LoadTheaters")',
data: { "groupId": groupId },
success: function (data) {
$('.theaters').multiselect('destroy');
$('.theaters').replaceWith($(data));
$('.theaters').multiselect('rebuild');
},
error: function (xhr) {
$('.theaters').multiselect('destroy');
$('.theaters').multiselect('rebuild');
}
});
}
});
});
If anyone can show me how to do this or at least point me in the right direction, I would much appreciate it. Thanks in advance.
Ok -- I got it to work. Here is what I was doing before:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').multiselect('destroy');
$('.userGroups').replaceWith($(data));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').multiselect('destroy');
$('.userGroups').multiselect('rebuild');
}
});
I made the following changes that maintained the userGroups dropdown so the onChange event would fire:
$.ajax({
url: '#Url.Action("LoadUserGroups")',
data: { "userName": userName },
success: function (data) {
$('.userGroups').empty();
$('.userGroups').append($(data).find('option'));
$('.userGroups').multiselect('rebuild');
},
error: function (xhr) {
$('.userGroups').empty();
$('.userGroups').multiselect('rebuild');
}
});
Works like it should now.

jQuery fileDownload conflicting with another jQuery plugin

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

Kendo UI, datagrid inserted row produces request multiple times

i have problem with Kendo data grid component.
I'm trying to add new row into grid and create remote request to API via create event.
Problem is that if i try to add new row after first request Kendo make 2 requests instead of the one.
I tried to find some solution for this using transport create and options.success method but without luck.
http://docs.telerik.com/kendo-ui/api/framework/datasource#configuration-transport.create
Could somebody tell to me what i'm doing wrong?
Thanks for any help.
Here is the code of the server response for create:
+ Response 200 (application/json)
{
"status": "OK",
"result":[
{
"id":22,
"username":"blahblah",
"name":"Thomas",
"surname":"Man",
"email":"to.mas.marny#gmail.com",
"created":"1399986964",
"role":"USER"
}
]
}
Here is the code of the method:
$scope.initGrid = function () {
// get access token from localstorage
var token = localStorage
.getItem($rootScope.lsTokenNameSpace);
// set pagination data
var paginationData = {
"token": token,
"data": {
"page": 1,
"items_per_page": 20
}
};
var dataPacket;
dataPacket = new kendo.data.DataSource({
transport: {
read: function (options) {
$.ajax({
url: $rootScope.apiBaseUrl + "user/list",
dataType: "json",
type: "POST",
data: JSON
.stringify(paginationData),
success: function (
response) {
console
.log("List of users succesfully obtained");
console
.log(response.result);
// pass response to
// model
options
.success(response);
// $notification.enableHtml5Mode();
},
error: function (error) {
console
.log("user list request error");
console.log(error);
$notification
.error(
"User list cannot be loaded",
"Please try again in a minute.");
}
});
},
update: function (options) {
console.log("Update");
options
.success("{\"test\":\"test\"}");
},
destroy: function (options) {
console.log("destroy");
options
.success("{\"test\":\"test\"}");
},
create: function (options) {
console.log("Create");
console.log(options.data);
$.ajax({
url: $rootScope.apiBaseUrl + "user/create",
dataType: "json",
type: "POST",
data: JSON
.stringify(options.data),
success: function (
response) {
console
.log("New user created");
console
.log(response.status);
// pass response to
// model
options
.success(response.result);
// $notification.enableHtml5Mode();
},
error: function (error) {
console.log("user list request error");
console.log(error);
$notification
.error(
"User cannot be created",
"Please try again in a minute.");
}
});
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
//batch : true,
//autoSync: true,
schema: {
data: "result",
model: {
id: "id",
fields: {
id: {
editable: false,
nullable: true
},
name: {
editable: true,
nullable: false
},
username: {
editable: true,
nullable: false
}
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataPacket,
filterable: true,
pageSize: 20,
pageable: true,
height: 550,
toolbar: ["create", "save", "cancel"],
columns: ["id", "name", "username", {
command: ["edit", "destroy"],
title: " ",
width: "200px"
}],
editable: "inline"
});
};
If you declare id inside model then you don't have to declare id inside model fields.
Also when you point
data: "result"
for the model you have to pass
options.success(response)
inside ajax's success function, not just
options.success(response.result)
I think if null is passed to the Datasource of the kendo Grid in the html helper, the Grid will be built in “remote data mode” rather than “local data mode”
and since the read Url is not set the current browser Url will be used for the read operation.
make sure to initialize the list in the Model before using it as a Datasource.

jquery callback function not accessing global function

I have 2 functions declared makeAjaxCall and editOrderDetails
editOrderDetails executes makeAjaxCall to go and get a json object with the results of the call.
function editOrderDetails()
{
makeAjaxCall(
baseurl+'/orderoutbound/editorderdetails',
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
function(data){
if(data.success)
{
$("#editOrderDetailsErrorDiv").html(successDiv(data.generalMessage));
$(".customerReferenceSpan").html(data.order.customerReference);
$(".emailSpan").html(data.order.emailAddress);
}else{
$("#editOrderDetailsErrorDiv").html(errorDiv(data.generalMessage));
$("#emailAddressErrorDiv").html(data.errors.emailAddress);
}
},
function(data) {
$("#editOrderDetailsErrorDiv").html(errorDiv("There was an error.."));
}
);
}
now i'm using a jquery dialog to work with
$("#editOrderDetailsDialog").dialog('destroy').dialog({
autoOpen: false,
title: 'Edit Order Details',
closeOnEscape: true,
width: 500,
height: 300,
buttons:{
"Save": function() { editOrderDetails(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
as my save call back function i'm trying to set my editOrderDetails function.
This however doesnt work and i'm guessing it has something to do with the scopeing.
i have tried declaring var editOrderDetails = function(){}; outside of any and all jquery doc ready functions
i have also tried window.editOrderDetails()
also instead of making a function wrapping the function call
i have tried putting the function into a variable var editOrderDetails = function(){};
then "save" : editOrderDetails
i'm at a loss. any ideas would be appreciated ?
PS yes the dialog works correctly. if i place an alert in the callback function it executes when i click save.
<script type="text/javascript">
<!--
var orderID = '<?= $this->orderID; ?>';
var customerID = '<?= $this->customerID; ?>';
//################ PAGE FUNCTIONS ################
//MAKE AN AJAX CALL
function makeAjaxCall(ajaxUrl, data, functionSuccess, functionFailure){
$.ajax(
{
type: "GET",
url: ajaxUrl,
contentType: "application/json; charset=utf-8",
data: data,
dataType: "json",
success: functionSuccess,
error: functionFailure
});
}
//END MAKE AN AJAX CALL
//EDIT ORDER DETAILS
function editOrderDetails()
{
makeAjaxCall(
baseurl+'/orderoutbound/editorderdetails',
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
function(data){
if(data.success)
{
$("#editOrderDetailsErrorDiv").html(successDiv(data.generalMessage));
$(".customerReferenceSpan").html(data.order.customerReference);
$(".emailSpan").html(data.order.emailAddress);
}else{
$("#editOrderDetailsErrorDiv").html(errorDiv(data.generalMessage));
$("#emailAddressErrorDiv").html(data.errors.emailAddress);
}
},
function(data) {
$("#editOrderDetailsErrorDiv").html(errorDiv("There was an error.."));
}
);
}
//END EDIT ORDER DETAILS
//################ END PAGE FUNCTIONS ################
$(function() {
// EDIT ORDER DETAILS DIALOG
$("#editOrderDetailsDialog").dialog('destroy').dialog({
autoOpen: false,
title: 'Edit Order Details',
closeOnEscape: true,
width: 500,
height: 300,
buttons:{
"Save": function() { editOrderDetails(); },
"Cancel": function() { $(this).dialog("close"); }
}
});
// END EDIT ORDER DETAILS DIALOG
});
//-->
</script>
You are missing a $ in the call to makeAjaxCall.
'orderID='+orderID+'&customerReference='+("#orderReference").val()+'&email='+$("#emailAddress").val(),
Becomes:
'orderID='+orderID+'&customerReference='+$("#orderReference").val()+'&email='+$("#emailAddress").val(),
This http://jsfiddle.net/jQRyq/8/ works fine for me, could you post a bit more of your code for context? Specifically where the editOrderDetails functions is defined.

Categories

Resources