I have these employee information which display if you click on the employee box. But sometimes the value of some fields returns null even if they have a value but when I retry it will return ok. Is this some code problem? here is my code...
First I store the elements into an object
var uamnumber = $(this).find(".box-list-agents-uamnumber").text();
var agentInfo = $(this).find(".box-list-agents-info").text().split("/");
var agentElement = {
txtUam: $("#search-txt-uam-number"),
txtFirstName: $("#search-txt-first-name"),
txtMiddleName: $("#search-txt-middle-name"),
txtLastName: $("#search-txt-last-name"),
txtContactNumber: $("#search-txt-contact-number"),
txtEmailAddress: $("#search-txt-email-address"),
txtClassification: $("#search-txt-classification"),
txtAgentStatus: $("#search-txt-agent-status"),
txtReasonResignation: $("#search-txt-reason-resignation"),
txtCsp: $("#search-txt-csp-name"),
txtProgramId: $("#search-txt-program-name"),
txtSite: $("#search-txt-site-name"),
txtBirthDate: $("#search-txt-birth-date"),
txtLiveDate: $("#search-txt-live-date"),
txtEndDate: $("#search-txt-end-date"),
txtProgram: $("#search-program-name")
};
var agentParam = {
uam: uamnumber,
csp: agentInfo[0],
program: agentInfo[1]
}
Dashboard_GetAgentInfo(agentParam, agentElement);
$("#search-well-tool-access").hide();
$("#search-well-agent-info").fadeIn();
and here is the function that has been called.
function Dashboard_GetAgentInfo(agentInfo,agentElement) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Dashboard_GetAgentInfo",
data: JSON.stringify(agentInfo),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var uamdetails = response.d;
var appendItem = "";
$.each(uamdetails, function (index, Dashboard_GetAgentInfoInfo) {
var uamnumber = Dashboard_GetAgentInfoInfo.uamnumber;
var firstname = Dashboard_GetAgentInfoInfo.firstname;
var middlename = Dashboard_GetAgentInfoInfo.middlename;
var lastname = Dashboard_GetAgentInfoInfo.lastname;
var contactnumber = Dashboard_GetAgentInfoInfo.contactnumber;
var emailaddress = Dashboard_GetAgentInfoInfo.emailaddress;
var csp = Dashboard_GetAgentInfoInfo.csp;
var cspid = Dashboard_GetAgentInfoInfo.cspid;
var program = Dashboard_GetAgentInfoInfo.program;
var programid = Dashboard_GetAgentInfoInfo.programid;
var site = Dashboard_GetAgentInfoInfo.site;
var siteid = Dashboard_GetAgentInfoInfo.siteid;
var birthdate = Dashboard_GetAgentInfoInfo.birthdate;
var livedate = Dashboard_GetAgentInfoInfo.livedate;
var enddate = Dashboard_GetAgentInfoInfo.enddate;
var classification = Dashboard_GetAgentInfoInfo.classification;
var agentStatus = Dashboard_GetAgentInfoInfo.agentstatus;
var reasonResignation = Dashboard_GetAgentInfoInfo.reasonresignation;
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
$(agentElement.txtMiddleName).val(middlename);
$(agentElement.txtLastName).val(lastname);
$(agentElement.txtContactNumber).val(contactnumber);
$(agentElement.txtEmailAddress).val(emailaddress);
$(agentElement.txtClassification).val(classification);
$(agentElement.txtAgentStatus).val(agentStatus);
$(agentElement.txtReasonResignation).val(reasonResignation);
$(agentElement.txtCsp).val(cspid)
$(agentElement.txtProgramId).val(programid);
$(agentElement.txtSite).val(siteid);
$(agentElement.txtBirthDate).val(birthdate);
$(agentElement.txtLiveDate).val(livedate);
$(agentElement.txtEndDate).val(enddate);
$(agentElement.txtProgram).text(program);
NumbersOnly();
});
},
error: function (XMLhttpRequest) {
alert("error in Dashboard_GetAgentInfo");
console.log(XMLhttpRequest);
}
});
}
and this is the web service that has been called
public List<Dashboard_GetAgentInfoDetails> Dashboard_GetAgentInfo(string uam, int csp, int program) /*int CSP, int Program*/
{
DataTable table = null;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "[Dashboard_GetAgentInfo]";
cmd.Parameters.AddWithValue("#uam", uam);
cmd.Parameters.AddWithValue("#csp", csp);
cmd.Parameters.AddWithValue("#program", program);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
table = this.dbConn.ExecuteDataTable(cmd);
Dashboard_GetAgentInfo_Details.Clear();
foreach (DataRow row in table.Rows)
{
Dashboard_GetAgentInfoDetails _list = new Dashboard_GetAgentInfoDetails();
_list.uamnumber = row["UAM #"].ToString();
_list.firstname = row["First Name"].ToString();
_list.middlename = row["Middle Name"].ToString();
_list.lastname = row["Last Name"].ToString();
_list.contactnumber = row["Contact Number"].ToString();
_list.emailaddress = row["Email Address"].ToString();
_list.csp = row["CSP"].ToString();
_list.cspid = Convert.ToInt32(row["CSPID"].ToString());
_list.program = row["Program"].ToString();
_list.programid = Convert.ToInt32(row["ProgramID"].ToString());
_list.site = row["Site"].ToString();
_list.siteid = Convert.ToInt32(row["SiteID"].ToString());
_list.birthdate = row["BirthDate"].ToString();
_list.livedate = row["LiveDate"].ToString();
_list.enddate = row["EndDate"].ToString();
_list.classification = Convert.ToInt32(row["Classification"].ToString());
_list.agentstatus = row["Agent Status"].ToString();
_list.reasonresignation = row["Reason Resignation"].ToString();
Dashboard_GetAgentInfo_Details.Add(_list);
}
return Dashboard_GetAgentInfo_Details;
}
does storing elements into an object and passing it as a parameter is a good practice of coding? and what may be the cause of the select having no value even if I when I try to console.log the value and it returns ok?
I think the problem is here:
$(agentElement.txtUam).val(uamnumber);
$(agentElement.txtFirstName).val(firstname);
...
You should do:
agentElement.txtUam.val(uamnumber);
agentElement.txtFirstName.val(firstname);
...
There is no need to use jquery selector $, because agentElement.txtUam is already one, also gathering elements inside an object is a best practice because you can't pass each one as a parameter.
The perfect answer to this is add a call back function so the dropbox have a option first before adding the val. Here is the idea of adding a callback function
function Filtering_GetSite(siteElement, callback) {
if (typeof (callBack) == "function") {
callBack();
}
}
the line checking of the callback parameter is to ensure that it its a function before executing so you can call the function like this Filtering_GetSite(sample) insted of Filtering_GetSite(sample,function(){}) when omiting the callback function
Related
I'm using Github Gists for a web playground I'm making as a side project. I load two json files into the editor. 1 handles all the libraries (jquery, bootstrap, etc:) and another for the users settings (fontsize, version, etc:)
So anyway I have this JSON named settings
var settings = gistdata.data.files["settings.json"].content
var jsonSets = JSON.parse(settings)
I parse and attempted to grab an object from the JSON and set it as a value of a input textbox.
Now console.log(jsonSets.siteTitle) works perfectly fine
but when I try to change the input dynamically...
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
The problem is it's not actually applying the value!
The only way I've been able to successfully apply the value is...
setTimeout(function() {
$("[data-action=sitetitle]").val(jsonSets.siteTitle).trigger("change")
}, 5000)
Which is ridiculously slow.
Does anyone know why it's not applying the value?
in addition.
How can I solve this problem?
var hash = window.location.hash.substring(1)
if (window.location.hash) {
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp"
}).success(function(gistdata) {
var libraries = gistdata.data.files["libraries.json"].content
var settings = gistdata.data.files["settings.json"].content
var jsonLibs = JSON.parse(libraries)
var jsonSets = JSON.parse(settings)
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value)
})
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle).trigger("change")
$("[data-value=version]").val(WeaveVersion).trigger("change")
$("[data-editor=fontSize]").val(editorFontSize).trigger("change")
$("[data-action=sitedesc]").val(WeaveDesc).trigger("change")
$("[data-action=siteauthor]").val(WeaveAuthor).trigger("change")
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
My problem was actually related to localStorage.
I cleared it localStorage.clear(); ran the ajax function after and it solved the problem.
var hash = window.location.hash.substring(1)
if (window.location.hash) {
localStorage.clear()
function loadgist(gistid) {
$.ajax({
url: "https://api.github.com/gists/" + gistid,
type: "GET",
dataType: "jsonp",
jsonp: "callback"
}).success(function(gistdata) {
var htmlVal = gistdata.data.files["index.html"].content
var cssVal = gistdata.data.files["index.css"].content
var jsVal = gistdata.data.files["index.js"].content
var mdVal = gistdata.data.files["README.md"].content
var settings = gistdata.data.files["settings.json"].content
var libraries = gistdata.data.files["libraries.json"].content
var jsonSets = JSON.parse(settings)
var jsonLibs = JSON.parse(libraries)
// Return font settings from json
var siteTitle = jsonSets.siteTitle
var WeaveVersion = jsonSets.version
var editorFontSize = jsonSets.editorFontSize
var WeaveDesc = jsonSets.description
var WeaveAuthor = jsonSets.author
$("[data-action=sitetitle]").val(siteTitle)
$("[data-value=version]").val(WeaveVersion)
$("[data-editor=fontSize]").val(editorFontSize)
$("[data-action=sitedesc]").val(WeaveDesc)
$("[data-action=siteauthor]").val(WeaveAuthor)
storeValues()
// Return settings from the json
$(".metaboxes input.heading").trigger("keyup")
// Return libraries from json
$.each(jsonLibs, function(name, value) {
$(".ldd-submenu #" + name).prop("checked", value).trigger("keyup")
})
// Set checked libraries into preview
$("#jquery").trigger("keyup")
// Return the editor's values
mdEditor.setValue(mdVal)
htmlEditor.setValue(htmlVal)
cssEditor.setValue(cssVal)
jsEditor.setValue(jsVal)
}).error(function(e) {
// ajax error
console.warn("Error: Could not load weave!", e)
})
}
loadgist(hash)
} else {
// No hash found
}
I have some data in a IndexedDB table that quite simply contains this data:
var Customers = [
{ ssn: "123-45-6666", name: "Andrew", age: 22, email: "andrew#hotmail.com" },
{ ssn: "555-66-7777", name: "Gail", age: 25, email: "gail#email.me" }
];
I then have this function to get data back from the IndexedDB:
function RetrieveTableRows(Table) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
return;
}
returnData.push(result.value);
result.continue();
};
return returnData;
}
I realise that it does not work because the onsuccess function is asynchronous, however I can't my head around a solution.
Simply, I want to be able to write:
var myCustomers = RetrieveTableRows('customers');
and be able to then use the variable myCustomers - is this possible?
I have tried using JQuery.deferred(); method but that didn't seem to work, and I know that I could possibly do something like this:
transaction.oncomplete = function() {
ReturnTableRows(returnData);
};
}
function ReturnTableRows(data) {
//do something with the array of data
}
but I can't work out how to pass this back to the myCustomers variable.
Using the deferred object you should be able to do something like this
function RetrieveTableRows(Table) {
var returnData = [];
//setup deferred object
var defer = $.Deferred();
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
//when done resolve the promise, you could also do more
//checking and reject the data so you can handle
//errors
defer.resolve(returnData);
//Make sure we exit the function once we run out of data!
return
}
returnData.push(result.value);
result.continue();
};
//return the promise
return defer.promise();
}
//########### then to use this ###########
//this is now a promise
var myCustomersPromise = RetrieveTableRows('customers');
var myCustomers;
//action todo when promise is resolved/rejected
$.when(myCustomersPromise ).done(function(data){
//do something with the data/assign it to you var here
myCustomers= data;
}).fail(function(data){
});
although i have not actually used indexedDB before so maybe misunderstanding how the query knows it is finished ( I am asssuming result.continue() called the onSuccess again and the result is false when it has gone through all the data) but this is the setup I use when doing anything asynchronously in my apps
An alternate method I've found that uses less code, is a lot simpler and doesn't require JQuery.
Setup:
// Create the function(s) to grab and store the data
var myCustomers;
var getData = {
customers: function(data) {
myCustomers = data
}
}
Call:
//Send the callback function we want into the retrieve function
trans.oncomplete = function (e) {
RetrieveTableRows('Customers', getData.customers)
};
Function:
function RetrieveTableRows(Table, Callback) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
// Send the information back to our specified function
Callback(returnData);
return
}
returnData.push(result.value);
result.continue();
};
}
I get that A in ajax is asynchronous. But I can't find an alternatives to what i'm trying to do.
I have a graph that I need to feed with a javascript array. This array is made from a csv import.
So I'm trying to make a function that return an array with the function recupCSV():
data = [];
objet function (data, objet) {
var jour = data[3].split("/");
var start = new Date(jour[2], jour[1], jour[0]);
var dtS = new Date(start.getFullYear(), start.getMonth(), start.getDate());
jour = data[4].split("/");
var end = new Date(jour[2], jour[1], jour[0]);
var dt = new Date(end.getFullYear(), end.getMonth(), end.getDate());
var workItem = {id: data[0],name: data[1],lane: data[2],start: dtS,end: dt ,desc: data[5]};
objet.push(workItem);
}
function recupCSV(data) {
donnee = [];
$.ajax({
url: "http://www.example.com/csvfile.csv",
aync: false,
success: function (csvd) {
csv_as_array = $.csv2Array(csvd);
for(var i in csv_as_array )
objet(csv_as_array[i],data);
},
dataType: "text",
complete: function () {
}
});
return data;
}
I can see many reasons why it doesn't work, but I can't see any that would.. ;)
Ok sorry for all this mess, here's the code that actualy works :
d3.csv("file.csv", function (error, data) {
csvAsArray = data;
localStorage.setItem('anobjectwithnoname', JSON.stringify(csvAsArray));
});
then in some function :
var csv = localStorage.getItem('anobjectwithnoname');
var csvAsArray = JSON.parse(csv);
this way i got the object out of the asynchronous "trap" ;)
sorry again for the messy code. please don't be to harsh with try and fail type of learning
Hi I'am working with Windows 8 app using Java Script
function fetchFromLiveProvider(currentList, globalList,value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
WinJS.xhr({url: feedUrl, responseType: "rss/json"
}).done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
});
}
function setOther(entries){
//some code here
}
I want to do is pass the entries in the fetchFromLiveProvider function to another function called setOther(entries){}. Thank you for any help...
Since WinJS.xhr returns a promise, you can do the following:
var entriesPromise = function fetchFromLiveProvider(currentList, globalList, value) {
feedburnerUrl = currentList.url,
feedUrl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json&num=999&q=" + encodeURIComponent(feedburnerUrl);
return WinJS.xhr({
url: feedUrl,
responseType: "rss/json"
});
}
function setOther(entries) {
entries.done(function complete(result) {
var jsonData = JSON.parse(result.response);
//console.log(JSON.stringify(jsonData));
var entries = jsonData.responseData.feed;
//some code here
})
}
setOther(entriesPromise);
I have an issue where I can't get to a variable inside a function:
EDIT
I forgot to add that I am setting this workerPage.grid = $("#grid").data("kendoGrid"); on the jQuery $(function(){});
I can't use claimsGird variable inside the save function, I have to referenec it by workerPage.grid. Not the other variables like viewModel work fine. Here is the snippet:
save = function () {
saif.kendoGridUtils.addModifiedDataItems(
viewModel.CompanionClaims.Updated,
viewModel.CompanionClaims.Added,
$("#grid").data("kendoGrid").dataSource.data()
);
$.ajax({
url: $("#contentForm").attr("action"),
data: JSON.stringify(viewModel),
type: "POST",
contentType: "application/json"
}).success(function (data) {
//syncs viewModel with changes in model
$.extend(viewModel, kendo.observable(data));
//rebinds the grid data source
claimsGrid.dataSource.data(viewModel.CompanionClaims.Rows);
Here is the full script:
var workerPage = (function () {
var viewModel = kendo.observable(#Html.Raw(Json.Encode(Model))),
claimsGrid = null,
deleteFirm = function (firmModel) {
firmModel.Name = "";
firmModel.AttorneyName = "";
firmModel.Address.Line1 = "";
firmModel.Address.Line2 = "";
firmModel.Address.City = "";
firmModel.Address.State = "OR";
firmModel.Address.ZipCode = "";
firmModel.Address.PlusFourCode = "";
firmModel.PhoneNumber = "";
firmModel.FaxNumber = "";
firmModel.ContactName = "";
},
bind = function () {
kendo.bind($("#main-content"), viewModel);
},
save = function () {
saif.kendoGridUtils.addModifiedDataItems(
viewModel.CompanionClaims.Updated,
viewModel.CompanionClaims.Added,
$("#grid").data("kendoGrid").dataSource.data()
);
$.ajax({
url: $("#contentForm").attr("action"),
data: JSON.stringify(viewModel),
type: "POST",
contentType: "application/json"
}).success(function (data) {
//syncs viewModel with changes in model
$.extend(viewModel, kendo.observable(data));
//rebinds the grid data source
claimsGrid.dataSource.data(viewModel.CompanionClaims.Rows);
//rebinds view elements to view model so changes are visible
//kendo.bind($("#main-content"), viewModel);
bind();
// Errors and Warnings
var results = messageUtils.parseMessages(
viewModel.Messages.Errors,
viewModel.Messages.Informationals,
viewModel.Messages.Warnings
);
var errs = $("#errors").html(results.errorMessages);
$("#informationals").html(results.informationalMessages);
$("#warnings").html(results.warningMessages);
$.each(saif.kendoGridUtils.processErrors(viewModel.CompanionClaims.Rows), function (i, message) {
errs.html(errs.html() + message + "<br>");
});
// End Errors and Warnings
});
},
deleteRow = function () {
var row = claimsGrid.select(),
rowDataItem = claimsGrid.dataItem(row),
rowIndex = $(row).index(),
addedItemIndex = $.inArray(rowDataItem, viewModel.CompanionClaims.Added);
//add to Deleted if not new
if (addedItemIndex == -1 && $.inArray(rowDataItem, viewModel.CompanionClaims.Rows) != -1) {
viewModel.CompanionClaims.Deleted.push(rowDataItem);
}
//remove from Added if exists
if (addedItemIndex != -1) {
viewModel.CompanionClaims.Added.splice(addedItemIndex, 1);
}
claimsGrid.removeRow(row);
//select the next row, eg. if you delete row 2, select the row that took that rows poisition after it was deleted.
claimsGrid.select(claimsGrid.tbody.find(">tr:eq(" + rowIndex + ")"));
};
return {
bind: bind,
deleteFirm: deleteFirm,
deleteRow: deleteRow,
grid: claimsGrid,
save: save,
viewModel: viewModel
};
}());
The issue is that claimsGrid is never set to anything other than null. And setting workerPage.grid won't change the value of claimsGrid -- it's not a pointer, just a copy.
You'll instead have to use a getter/setter. With newer browsers/engines, that can be done with get and set:
// ...
return {
// ...
get grid() {
return claimsGrid;
},
set grid(grid) {
claimsGrid = grid;
},
// ...
};
You can also define grid as a function:
// ...
function getOrSetGrid(grid) {
if (typeof newGrid === 'undefined') {
return claimsGrid;
} else {
claimsGrid = grid;
}
}
return {
// ...,
grid: getOrSetGrid,
// ...
};
// ...
// rather than: workerPage.grid = ...;
workerPage.grid(...);
Or split it into getGrid and setGrid functions.
Scope in javascript works differently than other languages like Java or C#. In your case claimsGrid is not in scope for the save function. Does this help? http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/