I have to upload some files, for each file api is being called. Now if user want to cancel the upload using cancel button in a dialog box.
Please suggest how to reach to this solution.
I am using react and javascript for the file upload.
File upload component is in a different component.
api call is at utils page as shown
_bulkUpload: function(query, rType,sucessCount,failureCount,name) {
Api._callAPI(Url.BULK_UPLOAD, 'POST', query, (type, dt) => {
if(type=="success"){
let data = dt.res_data;
dispatcher.dispatch({
type:'DRAFT_BULK_UPLOAD',
response: sucessCount,
name: name,
});
dispatcher.dispatch({
type:'SNACKBAR',
str: dt.res_str,
toastType:0,
});
/*dispatcher.dispatch({
type:'DRAFT_BULK_UPLOAD',
response: count
});*/
} else {
dispatcher.dispatch({
type:'BULK_FAILED',
response: failureCount,
name: name
});
dispatcher.dispatch({
type: 'SNACKBAR',
str: Api._showErrorMsg(dt.status,dt.responseJSON||'')
});
}
dispatcher.dispatch({
type: 'LOADER',
loader: false
});
}, rType);
},
Api._callAPI function is calling a component as shown.
_callAPI : function(url,method,data,target,cType){
if(data && data.org_id && ([Url.PRELOGIN_CREATE_SUPER_USER,Url.PRELOGIN_CREATE_USER].indexOf(url) !== -1)){
// data.org_id = this._getKey('org_id');
}
else{
if([Url.SSO_CHECK,Url.PRELOGIN_FETCH,Url.LOGIN,Url.PRELOGIN_SEND_OTP,Url.PRELOGIN_VERIFY_OTP,Url.PRELOGIN_VERIFY_EMAIL,Url.COUNTRYCODE_TYPEAHEAD].indexOf(url) === -1)
if(!this._getKey('id') || !this._getKey('value')){
return false;
}
}
$.ajax({
url: BASEURL+url,
method: method,
data: data,
processData: (cType == 'multipart/form-data' ? false :true),
dataType: (cType == 'multipart/form-data' ? '' :'json'),
beforeSend: (xhr) => {
if(this._getKey('id') && this._getKey('value')){
xhr.setRequestHeader('XYZ-ID',this._getKey('id'));
xhr.setRequestHeader('XYZ-VALUE',this._getKey('value'));
if (this._getKey('viewType') == 'Privileged') {
xhr.setRequestHeader('XYZ-HASROLE','Y');
}
else{
xhr.setRequestHeader('XYZ-HASROLE','N');
}
xhr.setRequestHeader('x-csrfvalue',Math.random());
if (this._getKey('delegation_bit') === 'true') {
xhr.setRequestHeader('XYZ-DELEGATOR', this._getKey('delegator_id'));
xhr.setRequestHeader('XYZ-DELEGATION-ID', this._getKey('delegation_id'));
}
}
},
contentType: cType ? false : "application/x-www-form-urlencoded",
success: (data,textStatus, jqXHR) => {
if(jqXHR.getResponseHeader('XYZ-ID')){
this._setKey('id',jqXHR.getResponseHeader('XYZ-ID'));
}
if(jqXHR.getResponseHeader('XYZ-VALUE')){
this._setKey('value',jqXHR.getResponseHeader('XYZ-VALUE'));
}
/*dispatcher.dispatch({
type: 'LOADER',
loader: false
});*/
target('success',data);
},
error: (jqXhr,textStatus,error) => {
dispatcher.dispatch({
type: 'LOADER',
loader: false
});
if(jqXhr.status == 401){
this._clearStorage();
// try {
// sessionStorage.setItem('lastVisitedPage', window.location.hash.split("#")[1].split("?")[0]);
// } catch (ex) {
// console.log("Does not support CRUD with Storage");
// }
this._redirectToLogin();
} else{
target('error',jqXhr,textStatus,error);
}
}
});
},
File Upload and api call part
_handleFileUpload(){
let {failedBillCounter,statusArr} = this.state;
let sucessCount = 0;
let failureCount = 0;
var count=failedBillCounter;
let newFiles = document.getElementById('myFile').files;
let arr = [];
if(newFiles.length > 25){
UserInfoStores.showToast(Errors.MAX_NO_OF_FILE);
document.getElementById('myFile').value = "";
return false;
}
this.setState({fileCount:newFiles.length})
document.getElementById('draftBillBar').style.display = 'block';
//let newData = new FormData();
for(let i=0;i< newFiles.length;i++){
let newData = new FormData();
let files = [];
let txn_attachments = [];
if(newFiles[i].size/(1024*1024) > 15){
count=count+1;
statusArr.push({name:newFiles[i].name,type:'failed'})
this.setState({
statusArr,
failedBillCounter:count,
failCounterFlag:true,
},()=>this.progressBar());
}
else{
newData.append('files-'+i,newFiles[i],newFiles[i].name);
txn_attachments.push('files-'+i);
newData.append('txn_attachments', txn_attachments);
newData.append('source', 'web');
newData.txn_attachments = JSON.stringify(txn_attachments);
DraftAction.draftBulkUpload(newData,'multipart/form-data', sucessCount,failureCount,newFiles[i].name)
}
}
}
you must make a function to cancel the upload make a global variable for your ajaxCall
var ajaxCall;
_callAPI : function(...) {
...
...
ajaxCall = $.ajax({ ... });
}
// make a function to call when user click the cancel upload button
_cancelAjaxCall : function() {
ajaxCall.abort();
}
hope it works...
Related
class ProductInfoDetailsViewModel {
constructor(parent, productInfoWindowId, inventoryId, productId, supplierId, store) {
this._parent = parent;
this._created = false;
this._productInfoWindowId = productInfoWindowId;
this._inventoryId = inventoryId;
this._productId = productId;
this._supplierId = supplierId;
this._store = store;
}
_getMvvmData(inventoryId, productId, supplierId) {
return new Promise(function (resolve, reject) {
$.ajax({
url: '/ProductRowInfoSite/GetInventoryControl',
data: {
'inventoryId': inventoryId,
'productId': productId,
'supplierId': supplierId,
},
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
resolve(result);
},
error: function (jqXHR, textStatus, errorThrown) {
reject([jqXHR, textStatus, errorThrown]);
},
type: 'POST',
});
});
}
async create() {
let self = this;
let userStore = new UserStore();
//productInfoTextGrid
this._productInfoDetailsViewModel = kendo.observable({
value: {},
close: function () {
//$("#generalProductInfoWindow").data("kendoWindow").close();
//closeWindow();
},
not: function (value) {
return !this.get(value);
},
save: function (e) {
let productInfoTextGrid = $(self._productInfoWindowId + ' ' + '#productInfoTextGrid').data('kendoGrid');
/* productInfoTextGrid.saveChanges();*/
let orderUnitsGrid = $(self._productInfoWindowId + ' ' + '#orderUnitsGrid').data('kendoGrid');
let selectedRefHistProd = null;
try {
selectedRefHistProd = this.get('value.SelectedRefHistProd').ProductId;
} catch (error) {
// may be set to null and that's fine/TK.
}
var data = {
ProductId: self._productId,
InventoryId: self._inventoryId,
SupplierId: self._supplierId,
Fmean: this.get('value.Fmean'),
FMAD: this.get('value.FMAD'),
FTrend: this.get('value.FTrend'),
SelectedSeason: this.get('value.SelectedSeason').SeasonId,
MinQuantity: this.get('value.MinQuantity'),
SelectedOrderUnitNo: this.get('value.SelectedOrderUnit').UnitNo,
LeadTime: this.get('value.LeadTime'),
LeadTimeDeviation: this.get('value.LeadTimeDeviation'),
StockKeepInterest: this.get('value.StockKeepInterest'),
MaxLevel: this.get('value.MaxLevel'),
MinLevel: this.get('value.MinLevel'),
OrderQuantity: this.get('value.OrderQuantity'),
ReorderLevel: this.get('value.ReorderLevel'),
EnableManualSetRAndQ: this.get('value.EnableManualSetRAndQ'),
ForecastError: this.get('value.ForecastError'),
SelectedHistoryProductId: selectedRefHistProd,
};
var dataString = JSON.stringify(data);
$.ajax({
url: '/ProductRowInfoSite/SaveParameters',
data: {
data: dataString,
},
dataType: 'json',
// "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
//options.success(result);
self._store.dispatch({ type: ActionProductInfoWindow.Saving });
self._parent.refreshParentGrids();
},
error: function (result) {
displayAjaxError(result);
},
type: 'POST',
});
let userStore = new UserStore();
let finishSaved = userStore.translatedString('SOLOSupplier.ProductInfoWindows.FinishSaved');
displaySuccess(finishSaved);
productInfoTextGrid.saveChanges();
orderUnitsGrid.saveChanges();
},
recalc: function () {
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
var a = validator.validate();
},
products: new kendo.data.DataSource({
type: 'json',
serverFiltering: true,
pageSize: 100,
transport: {
read: function (options) {
$.ajax({
url: '/ProductRowInfoSite/GetProductInventoryList',
data:
{
'inventoryId': self._inventoryId,
'productId': self._productId,
'data': options.data,
},
//"filter": filter
dataType: 'json', // "jsonp" is required for cross-domain requests; use "json" for same-domain requests
success: function (result) {
// notify the data source that the request succeeded
options.success(result.HistProducts);
},
error: function (result) {
// notify the data source that the request failed
options.error(result);
},
type: 'POST',
});
},
parameterMap: function (data, type) {
return kendo.stringify($.extend({ 'text': $(data.filter.filters).get(0).value }, data));
},
},
}),
isEnabled: true,
onValidate: function (e) {
console.log('onValidate');
let maxLevel = this.get('value.MaxLevel');
let minLevel = this.get('value.MinLevel');
let userStore = new UserStore();
let validationErrorMessage = userStore.translatedString('uctrlSupplierWeb.MaxLevelMinLevelWarning');
let validator = $(self._productInfoWindowId).kendoValidator({
messages: {
custom: validationErrorMessage,
},
rules: {
custom: function (input) {
if (input.is('[name=minLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=minLevelParameter]') && input.val() !== '' && maxLevel !== null) {
return maxLevel > minLevel;
}
if (input.is('[name=maxLevelParameter]') && input.val() === '') {
return true;
} else if (input.is('[name=maxLevelParameter]') && input.val() !== '' && minLevel !== null) {
return maxLevel > minLevel;
} else {
return true;
}
},
},
},
).data('kendoValidator');
if (validator.validate() === true) {
self._store.dispatch({ type: ActionProductInfoWindow.Changing });
} else {
self._store.dispatch({ type: ActionProductInfoWindow.Cancelling });
}
},
});
kendo.bind($(self._productInfoWindowId + ' ' + '#tabInventoryControl'), self._productInfoDetailsViewModel);
try {
let result = await self._getMvvmData(self._inventoryId, self._productId, self._supplierId);
self._productInfoDetailsViewModel.products.read();
self._productInfoDetailsViewModel.set('value', result);
if (result.UnitsOnOrderAfterLeadtime === true) {
if ($(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox')) {
let widget = $(self._productInfoWindowId + ' ' + '#valueUnitsOnOrder').data('kendoNumericTextBox');
widget.wrapper.find('input').addClass('lightRed');
}
}
if ($(self._productInfoWindowId + ' ' + '#minLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#minLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
if ($(self._productInfoWindowId + ' ' + '#maxLevelParameterId').data('kendoNumericTextBox')) {
$(self._productInfoWindowId + ' ' + '#maxLevelParameterId')
.data('kendoNumericTextBox')
.min(result.MinLevelDefault);
}
var validator = $(self._productInfoWindowId).kendoValidator().data('kendoValidator');
validator.validate();
let element = $(self._productInfoWindowId);
window.kendo.ui.progress(element, false);
} catch ([jqXHR, textStatus, errorThrown]) {
displayAjaxError(jqXHR, textStatus, errorThrown);
productInfoDetailsViewModel.set('value', []);
window.kendo.ui.progress(element, false);
}
}
}
Saving edits in product info modal deletes used filters on products grid
if (productNo === null) {
let newFilter = await self._getFilterOnlyFromLocalStorage();
let totalFilter = $(self._gridId).data("kendoGrid").dataSource.filter();
totalFilter.filters.push.apply(totalFilter.filters, newFilter.filters);
$(self._gridId).data("kendoGrid").dataSource.filter(newFilter);
self._setPredefinedFilterButton(self);
}
}
I am beginner in JS. I have this sample array:
{"record-164": {"tomany": true, "fileName": "164"},"record-165": {"tomany": true, "fileName": "165"}}
and code JS:
var data = JSON.parse(json);
if (data["tomany"] == true && data["fileName"] !=""){
var fileName = data["fileName"];
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
type: 'POST',
url: '{{ route('deleteDJS') }}?id=' + fileName + '&type={{ $pageType }}',
data: {filename: fileName, id: fileName, type: '{{ $pageType }}'},
success: function (data) {
console.log("Delete file" +fileName);
refreshFileList();
//updatePhotoList();
},
error: function (e) {
console.log(e);
}
});
alert('Limit plików został przekroczony. Możesz dodać maksymalnie: ');
return;
}
The above code does not work correctly.
I would like the js script to delete it when the file has the parameter: tomany == true.
The delete function works correctly.
Problem is with file name and tomany parameters - I have many files - not one to delete/parse.
How can I repair this?
Use for in to iterate your object as below.
for(var item in data){
if (data[item]["tomany"] == true && data[item]["fileName"] !=""){
// perform your task here
}
}
First that is an object its not array.
You can distinguish object and array using this
starts with { -> object
example
const d = {'name':'your-name', 'age':23};
starts with [ -> array
const d_array = [{'name':'your-name', 'age':23},{'name':'your-name-2', 'age':26}];
You can iterate your object like this and then do the ajax.
const data = {"record-164": {"tomany": true, "fileName": "164"},"record-165": {"tomany": true, "fileName": "165"}}
for(let key in data){
console.log(data[key]["tomany"]);
console.log(data[key]["fileName"]);
}
Instead of iterating over the data and doing an AJAX call if the conditions are met it might be better to split up the code so you're doing one job at a time.
1) Iterate over the object and produce an array of AJAX promises based on the conditions.
2) Use jQuery's $.when to wait until all the calls have been made and then
3) Update the file list based on the results
const data = {"record-164": {"tomany": true, "fileName": "164"}, "record-165": {"tomany": true, "fileName": "165"}};
function doFetch(filename) {
return $.ajax({ ... });
}
function getPromises(data) {
return Object.keys(data).reduce((acc, obj) => {
const { tomany, fileName } = obj;
if (tomany && filename){
const promise = doFetch(filename);
return acc.concat(promise);
}
return acc;
}, []);
}
$.when.apply(null, getPromises()).then(result => {
updateFilenames(result);
});
Iterate the data object and access tomany field of each object to decide on deletion.
Object.keys(data).forEach(key => {
console.log(key);
if (data[key]["tomany"] == true && data[key]["fileName"] != "") {
var fileName = data[key]["fileName"];
console.log("Going to delete file: " + fileName);
}
});
Here is your modified code. I have commented out the actual API call part to make it executable.
var json = '{ "record-164": { "tomany": true, "fileName": "164" }, "record-165": { "tomany": true, "fileName": "165" } }';
var data = JSON.parse(json);
function doSomething() {
Object.keys(data).forEach(key => {
console.log(key);
if (data[key]["tomany"] == true && data[key]["fileName"] != "") {
var fileName = data[key]["fileName"];
console.log("Going to delete file: " + fileName);
// $.ajax({
// headers: {
// 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
// },
// cache: false,
// type: 'POST',
// url: '{{ route("deleteDJS") }}?id=' + fileName + '&type={{ $pageType }}',
// data: { filename: fileName, id: fileName, type: '{{ $pageType }}' },
// success: function (data) {
// console.log("Delete file" + fileName);
// refreshFileList();
// //updatePhotoList();
// },
// error: function (e) {
// console.log(e);
// }
// });
console.log('Limit plików został przekroczony. Możesz dodać maksymalnie: ');
return;
}
});
}
doSomething();
You can do something like this.
var json = {
"record-164": {
"tomany": true,
"fileName": "164"
},
"record-165": {
"tomany": true,
"fileName": "165"
}
}
function cleanJson(data, keys) {
for (let i in data) {
if (keys.includes(i)){
delete data[i];
//Do you file delete here
}else if (typeof data[i] === 'object') cleanJson(data[i], keys)
}
}
cleanJson(json, 'tomany')
console.log(json)
I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}
I have an $.ajax function on my page to populate a facility dropdownlist based on a service type selection. If I change my service type selection back and forth between two options, randomly the values in the facility dropdownlist will remain the same and not change. Is there a way to prevent this? Am I doing something wrong?
Javascript
function hydrateFacilityDropDownList() {
var hiddenserviceTypeID = document.getElementById('<%=serviceTypeID.ClientID%>');
var clientContractID = document.getElementById('<%=clientContractID.ClientID%>').value;
var serviceDate = document.getElementById('<%=selectedServiceDate.ClientID%>').value;
var tableName = "resultTable";
$.ajax({
type: 'POST',
beforeSend: function () {
},
url: '<%= ResolveUrl("AddEditService.aspx/HydrateFacilityDropDownList") %>',
data: JSON.stringify({ serviceTypeID: TryParseInt(hiddenserviceTypeID.value, 0), clientContractID: TryParseInt(clientContractID, 0), serviceDate: serviceDate, tableName: tableName }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
a(data);
}
,error: function () {
alert('HydrateFacilityDropDownList error');
}
, complete: function () {
}
});
}
function a(data) {
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
var tableName = "resultTable";
if (facilityDropDownList.value != "") {
selectedFacilityID = facilityDropDownList.value;
}
$(facilityDropDownList).empty();
$(facilityDropDownList).prepend($('<option />', { value: "", text: "", selected: "selected" }));
$(data.d).find(tableName).each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
$(facilityDropDownList).append(option);
});
if ($(facilityDropDownList)[0].options.length > 1) {
if ($(facilityDropDownList)[0].options[1].text == "In Home") {
$(facilityDropDownList)[0].selectedIndex = 1;
}
}
if (TryParseInt(selectedFacilityID, 0) > 0) {
$(facilityDropDownList)[0].value = selectedFacilityID;
}
facilityDropDownList_OnChange();
}
Code Behind
[WebMethod]
public static string HydrateFacilityDropDownList(int serviceTypeID, int clientContractID, DateTime serviceDate, string tableName)
{
List<PackageAndServiceItemContent> svcItems = ServiceItemContents;
List<Facility> facilities = Facility.GetAllFacilities().ToList();
if (svcItems != null)
{
// Filter results
if (svcItems.Any(si => si.RequireFacilitySelection))
{
facilities = facilities.Where(f => f.FacilityTypeID > 0).ToList();
}
else
{
facilities = facilities.Where(f => f.FacilityTypeID == 0).ToList();
}
if (serviceTypeID == 0)
{
facilities.Clear();
}
}
return ConvertToXMLForDropDownList(tableName, facilities);
}
public static string ConvertToXMLForDropDownList<T>(string tableName, T genList)
{
// Create dummy table
DataTable dt = new DataTable(tableName);
dt.Columns.Add("OptionValue");
dt.Columns.Add("OptionText");
// Hydrate dummy table with filtered results
if (genList is List<Facility>)
{
foreach (Facility facility in genList as List<Facility>)
{
dt.Rows.Add(Convert.ToString(facility.ID), facility.FacilityName);
}
}
if (genList is List<EmployeeIDAndName>)
{
foreach (EmployeeIDAndName employeeIdAndName in genList as List<EmployeeIDAndName>)
{
dt.Rows.Add(Convert.ToString(employeeIdAndName.EmployeeID), employeeIdAndName.EmployeeName);
}
}
// Convert results to string to be parsed in jquery
string result;
using (StringWriter sw = new StringWriter())
{
dt.WriteXml(sw);
result = sw.ToString();
}
return result;
}
$get return XHR object not the return value of the success call and $get function isn't synchronous so you should wait for success and check data returned from the call
these two lines do something different than what you expect
var facilityDropDownList = $get('<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>');
var selectedFacilityID = $get('<%= selectedFacilityID.ClientID%>').value;
change to something similar to this
var facilityDropDownList;
$.ajax({
url: '<%=servicesFormView.FindControl("facilityDropDownList").ClientID%>',
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
facilityDropDownList= data;
}
});
I 'm beginner in sencha touch 2 and i need to call webservice.The code of web service is:
public function loginAction()
{
$request = $this->getRequest();
$username = $request->request->get('username');
$password= $request->request->get('password');
$success=false;
$token="error";
$error="test";
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('username' => $username));
if (! $user)
{
$token="username not exists";
$success=false;
}
else
{
$password_user=$user->getPassword();
$factory = $this->get('security.encoder_factory');
$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword($password, $user->getSalt());
if ($password!=$password_user)
{
$token="password incorrect";
$success=false;
}
else
{
$token="logged";
$success=true;
}
}
$info= array("token" => $token);
$res=array("success"=> $success);
$res = array("status"=> $res,
"resultat"=>$info
);
$serializer = $this->get('jms_serializer');
$response = $serializer->serialize($res,'json');
return new Response($response);
}
and i make in project sencha a view: Login.js and a controller: Login.js. The problem is in calling the web service and the code in controller Login.js:
Ext.define('Sample.controller.Login', {
extend: 'Ext.app.Controller',
config: {
refs: {
loginView: 'loginview',
mainMenuView: 'mainmenuview'
},
control: {
loginView: {
signInCommand: 'onSignInCommand'
},
mainMenuView: {
onSignOffCommand: 'onSignOffCommand'
}
}
},
// Session token
sessionToken: null,
// Transitions
getSlideLeftTransition: function () {
return { type: 'slide', direction: 'left' };
},
getSlideRightTransition: function () {
return { type: 'slide', direction: 'right' };
},
onSignInCommand: function (view, username, password) {
console.log('Username: ' + username + '\n' + 'Password: ' + password);
var me = this,
loginView = me.getLoginView();
if (username.length === 0 || password.length === 0) {
loginView.showSignInFailedMessage('Please enter your username and password.');
return;
}
loginView.setMasked({
xtype: 'loadmask',
message: 'Signing In...'
});
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
username: username,
password: password
},
success: function (response) {
var loginResponse = Ext.JSON.decode(response.responseText);
if (loginResponse.success === "true") {
// The server will send a token that can be used throughout the app to confirm that the user is authenticated.
me.sessionToken = loginResponse.sessionToken;
me.signInSuccess(); //Just simulating success.
} else {
me.signInFailure(loginResponse.message);
console.log('erreur.');
}
},
failure: function (response) {
me.sessionToken = null;
me.signInFailure('Login failed. Please try again later.');
}
});
},
signInSuccess: function () {
console.log('Signed in.');
var loginView = this.getLoginView();
mainMenuView = this.getMainMenuView();
loginView.setMasked(false);
Ext.Viewport.animateActiveItem(mainMenuView, this.getSlideLeftTransition());
},
singInFailure: function (message) {
var loginView = this.getLoginView();
loginView.showSignInFailedMessage(message);
loginView.setMasked(false);
},
onSignOffCommand: function () {
var me = this;
Ext.Ajax.request({
url: 'http://localhost/dawinilastversion/web/app_dev.php/api/login',
method: 'post',
params: {
sessionToken: me.sessionToken
},
success: function (response) {
// TODO: You need to handle this condition.
},
failure: function (response) {
// TODO: You need to handle this condition.
}
});
Ext.Viewport.animateActiveItem(this.getLoginView(), this.getSlideRightTransition());
}
});
And the web service login work with success:
you need to go one step deeper into the JSON response:
if (loginResponse.status.success === true)
and check against the bool true not the string true