I've a script using navigator's local storage valuesand i've developped a web service that sends me the values, the only issue here is that i dont need it to send me Null results, this is the Function:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem("pClickVirement");
var pLinkCarteBancaire = sessionStorage.getItem("pLinkCarteBancaire");
var pLinkRechargePaiementFactureTelecom = sessionStorage.getItem("pLinkRechargePaiementFactureTelecom");
var pPaiementVignetteImpotTaxe = sessionStorage.getItem("PaiementVignetteImpotTaxe");
var pLinkPaiementFactureEauElectricite = sessionStorage.getItem("pPaiementFactureEauElectricite");
var pLinkServiceFatourati = sessionStorage.getItem("pCatchLinkServiceFatourati");
var pLinkCihExpress = sessionStorage.getItem("pCatchLinkCihExpress");
var pLinkEdocuments = sessionStorage.getItem("pCatchLinkEdocuments");
var lChannelId = "01";
var lServiceId = "900120";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
alert(lClientId);
var lData;
var lCollect;
console.log(lClientId);
lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom + " | " + pPaiementVignetteImpotTaxe + " | " + pLinkPaiementFactureEauElectricite + " | " + pLinkServiceFatourati + " | " + pLinkCihExpress + " | " + pLinkEdocuments;
console.log(lData);
alert(lData);
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:9097/CatchEvent.asmx/CollectData",
data: JSON.stringify({ "pData": lDataCollected }),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
alert('success');
}
},
error: function (exception) {
alert('Exeption : ' + exception);
}
});
sessionStorage.clear();
}
the results are like this :
Null || 300123 || 900452 || Null || Null || 26332
what should i do to not show the Null results ?
Given that lDataCollected is an string you can convert it to an array using split() and easily make a filter() excluding the 'Null' values from the array and finally join() to make an string again:
var lDataCollected = 'Null || 300123 || 900452 || Null || Null || 26332';
var result = lDataCollected
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
console.log(result);
Than, the final solution:
function SendNeedHelpLinkTrace() {
var pLinkVirement = sessionStorage.getItem('pClickVirement'),
pLinkCarteBancaire = sessionStorage.getItem('pLinkCarteBancaire'),
pLinkRechargePaiementFactureTelecom = sessionStorage.getItem('pLinkRechargePaiementFactureTelecom'),
pPaiementVignetteImpotTaxe = sessionStorage.getItem('PaiementVignetteImpotTaxe'),
pLinkPaiementFactureEauElectricite = sessionStorage.getItem('pPaiementFactureEauElectricite'),
pLinkServiceFatourati = sessionStorage.getItem('pCatchLinkServiceFatourati'),
pLinkCihExpress = sessionStorage.getItem('pCatchLinkCihExpress'),
pLinkEdocuments = sessionStorage.getItem('pCatchLinkEdocuments'),
lChannelId = '01',
lServiceId = '900120',
lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value,
lData = pLinkVirement + ' | ' + pLinkCarteBancaire + ' | ' + pLinkRechargePaiementFactureTelecom + ' | ' + pPaiementVignetteImpotTaxe + ' | ' + pLinkPaiementFactureEauElectricite + ' | ' + pLinkServiceFatourati + ' | ' + pLinkCihExpress + ' | ' + pLinkEdocuments,
lDataCollectedString = lClientId + ';' + lChannelId + ';' + lServiceId + ';' + lData,
getLDataCollected = function(str) {
var str
.split(' || ')
.filter(function(item) {
return item !== 'Null';
})
.join(' || ');
};
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://localhost:9097/CatchEvent.asmx/CollectData',
data: JSON.stringify({
'pData': getLDataCollected(lDataCollectedString)
}),
dataType: 'json',
async: true,
success: function(data, textStatus) {
if (textStatus === 'success') {
alert('success');
}
},
error: function(exception) {
alert('Exeption:' + exception);
}
});
sessionStorage.clear();
}
As commented by #hindmost, you should create an array of keys that you need to send and loop through them.
But my personal recommendation, send object instead. This way you will know what is empty and what is not.
Sample Code
// map of keys to fetch
var keysToSend = [
'pClickVirement'
'pLinkCarteBancaire'
'pLinkRechargePaiementFactureTelecom'
'PaiementVignetteImpotTaxe'
'pPaiementFactureEauElectricite'
'pCatchLinkServiceFatourati'
'pCatchLinkCihExpress'
'pCatchLinkEdocuments'
]
// Loop to concatinate
var data = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
// Check validity
function isEmpty(val){
return val === undefined || val === null;
}
Do an OR check
Assuming lData = pLinkVirement + " | " + pLinkCarteBancaire + " | " + pLinkRechargePaiementFactureTelecom produces Null || 300123 || 900452
Since you're getting the data from sessionStorage, the data will be stored as String, hence do a JSON.parse and do the following
NOTE:(incase the string is Null , then do String.toLowerCase() before JSON.parse())
lData = (pLinkVirement || '') + " | " + (pLinkCarteBancaire || '') + " | " + (pLinkRechargePaiementFactureTelecom || '')
Say you got the data pLinkVirement from sessionStorage as Null, do the following
pLinkVirement = pLinkVirement.toLowerCase()
pLinkVirement = JSON.parse(pLinkVirement)
pLinkVirement = (pLinkVirement || '')
Related
I am manipulating string to display in UI, Data is being dynamically with below code sometime i don't get header and details so how to make IHeader and IResponse optional for the string concatenation below.
if i dont have IHeader it will break at IHeader.id and throw exception i want to display whatever data is available to render.
main.js
const data = [{
id: "header",
name: "IHeader"
}, {
id: "param",
name: "IParams"
}, {
id: "details",
name: "IResponse"
}]
function buildText(data) {
var IParams;
var IResponse;
var IHeader;
for (var item of data) {
if (item.id === "param") {
IParams = item;
} else if (item.id === "header") {
IHeader = item;
} else if (item.id === "details") {
IResponse = item;
}
}
var text = '';
text += app + '.setConfig({\n' + "env:" + getEnv() + '\n});' + '\n\n';
text += 'let param:' + IParams.name + ' ' + '=' + '' + JSON.stringify(request, null, 4) + ';\n\n';
text += ref + '(' + 'param,(result:' + ' ' + '{' + '\n' + IHeader.id + ':' + IHeader.name + '\n' + IResponse.id + ':' + IResponse.name + '\n' + '})' + ' ' +
' => {\n console.log(result); \n});';
}
1 - You can try to create an object with empty values. That'll prevent the exception.
emptyObject = {id: ""} // more empty keys, if there is
IParam = (item.id === "param") ? item : emptyObject
2 - Or ignore that concatenation of the variable if undefined or null.
if (Iparam) {
// concatenation ..
}
I have a problem. I have features to sort, filter and search and when textarea of searchPhrase is null I have a problem:
Error: error https://localhost/cases/caselistsorted/no-filter/search_customer//casetype/desc
And I can't use sort and filter when searchPhrase is null.
How I can fix it?
This is my code:
function sendParam(element) {
var filterSelect = $("#filterSelect").val();
var searchOption = $("#searchOption").val();
var searchPhrase = $("#searchPhrase").val();
var params1 = $(element).attr("sort");
var params2 = $(element).attr("order");
var url = "{{restUrl}}cases/caselistsorted/" + filterSelect
+ "/" + searchOption + "/"+searchPhrase + "/"
+ params1 + "/" + params2;
$.ajax({
type: 'GET',
url: url,
data: null,
dataType: 'json',
success: function (data) {
if (data != null) {
console.log(url);
$(".case-list").html(data["code"]);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Error: " + textStatus + " " + url);
}
});
}
$(document).on('ready', function(){
$('.button-sort').on('click', function() {
sendParam(this);
});
$('#filterSelect').change(function () {
sendParam(this);
});
});
function customerSearch() {
sendParam(this);
}
function customerSearchTextInput(event) {
if (event.which == 13 || event.keyCode == 13) {
customerSearch();
return false;
} else if (event.which == 27 || event.keyCode == 27) {
customerSearchClear();
return false;
}
return true;
}
function customerSearchClear() {
var searchPhrase = $("#searchPhrase").val("");
console.log("FieldClear!");
}
When I write in searchPhrase somethink e.g "hello" I have such an outcome:
"https://localhost/cases/caselistsorted/no-filter/search_customer/hello/createDate/asc"
PHP Code :
if ($filter && $searchOption && $searchPhrase && $sortField == "createDate" && $order == "asc") {
usort($caseList, function ($a, $b) {
/* #var $a CMCase */
/* #var $b CMCase */
$time1 = strtotime($a->createDate);
$time2 = strtotime($b->createDate);
return $time1 > $time2;
});
You could check if searchPhrase is not null by adding a ternary
(searchPhrase ? "/" + searchPhrase : "")
and only add the / (and searchPhrase) if it holds a value:
var url = "{{restUrl}}cases/caselistsorted/" + filterSelect
+ "/" + searchOption + (searchPhrase ? "/" + searchPhrase : "")
+ "/" + params1 + "/" + params2;
If you can use arrays, you can try something like this.
Note, its better to have a dataStructure, an object or an array. Object will not have order, so either you will have to use map or if you are on ES6, use set
var data = [];
/*data.push($("#filterSelect").val());
data.push($("#searchOption").val());
data.push($("#searchPhrase").val());
data.push($(element).attr("sort"));
data.push($(element).attr("order"));*/
data.push("test");
data.push("");
data.push("Hello");
data.push("World");
data.push("");
function isNotEmpty(val){
return !(
val === undefined ||
val === null ||
val.toString().trim().length === 0
)
}
var qsString = data.filter(isNotEmpty).join("/");
console.log(qsString)
I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.
I have a javascript code as below
var xReg = '<region><width>' + $("#txtWidth").val() + '</width> <height>' + $("#txtHeight").val() + '</height><float>' + $("#floats").val() + '</float><contenttype>' + $("#contenttype").val() + '</contenttype><style>' + rgnStyle + '</style></region>';
$.ajax({
type: "POST",
url: "myurl/addRegion",
data: "{pubId: '" + Number($("#pubs").val()) + "',section: '" + $("#sections option:selected").text() + "',layoutW: '" + Number($("#txtLayoutW").val()) + "',layoutH: '" + Number($("#txtLayoutH").val()) + "',bSubReg: '" + Boolean($("#chkSubRegion").is(':checked')) + "',parentRegId: '" + Number(parentRgn) + "',sXmlRegion: '" + xReg.toString() + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result) {
document.body.style.cursor = 'pointer';
if (result.d == -1) {
$("#errMsg").text("Failed to create new region");
}
else {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
},
error: function (result) {
if (result.status == 200 && result.statusText == 'OK') {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
else {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
},
async: true
});
Server code as below
[WebMethod]
public int addRegion(int pubId, string section, int layoutW, int layoutH, bool bSubReg, int parentRegId, string sXmlRegion)
{
string path = Server.MapPath("~");
path = Path.Combine(path, "Published");
path = Path.Combine(path, pubId.ToString());
path = Path.Combine(path, section);
XmlDocument doc = new XmlDocument();
int rgnCount = 0;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "layout.xml");
if (!File.Exists(path))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode templateNode = doc.CreateElement("layout");
doc.AppendChild(templateNode);
XmlNode xNodeW = doc.CreateElement("width");
xNodeW.AppendChild(doc.CreateTextNode(layoutW.ToString()));
XmlNode xNodeH = doc.CreateElement("height");
xNodeH.AppendChild(doc.CreateTextNode(layoutH.ToString()));
}
else
{
doc.Load(path);
doc.DocumentElement.SelectSingleNode("/layout/width").InnerText = layoutW.ToString();
doc.DocumentElement.SelectSingleNode("/layout/height").InnerText = layoutH.ToString();
}
XmlElement root = doc.DocumentElement;
XmlNode xParent = root;
if (bSubReg)
{
xParent = root.SelectSingleNode("/layout/region[id='" + parentRegId.ToString() + "']");
rgnCount = xParent.SelectNodes("/region").Count;
}
else
{
rgnCount = root.SelectNodes("/Layout/region").Count;
}
rgnCount++;
XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
docFragment.InnerXml = sXmlRegion;
XmlNode xID = doc.CreateElement("id");
xID.AppendChild(doc.CreateTextNode(rgnCount.ToString()));
docFragment.FirstChild.AppendChild(xID);
xParent.AppendChild(docFragment);
doc.Save(path);
return rgnCount;
}
catch (Exception eX)
{
return -1;
}
}
The call is going to server from client. And no issues I could find in server code till last return statement while I debugged it. In the javascript debugging I found that after ajax call is always going to error callback function. Can anyone suggest whats wrong with the code.
Thanks & Appreciate Your Time.
I found the bug in my code there is issue with below lines of code
},
async: true
at the end of error: callback function
I removed the line async: true and it worked
I have the following javascript.
Problem is if I enter one row in the table "ingredients" but I am getting 2 rows in the resulting pass to controller action after seralising into my C# object. But the second object is null?
I checked the javascript and the variable "cnt" is 1 not 2.
Why would that be?
Malcolm
[code]
$("#Save").click(function () {
var title = $("#recipetitle").val();
var category = $("#category").val();
var preptime = $("#prepTime").val();
var preptimeperiod = $("#lstPrepTime").val();
var cooktime = $("#cookTime").val();
var cooktimeperiod = $("#lstCookTime").val();
var rating = $("#rating").val();
var method = $("#method").val();
var jsontext = '{ "RecipeTitle": "' + title + '",';
jsontext += '"CategoryID":' + category + ',';
jsontext += '"PrepTime":' + preptime + ',';
jsontext += '"PrepTimePeriod":"' + preptimeperiod + '",';
jsontext += '"CookTime":' + cooktime + ',';
jsontext += '"CookTimePeriod":"' + cooktimeperiod + '",';
jsontext += '"Rating":' + rating + ',';
jsontext += '"Method":"' + method + '",';
var ing = "";
var cnt = 0;
$("#ingredients tr.ingredientdata").each(function () {
if ($("td.ingredient", this).text() != "") {
ing += '{ "IngredientName": "' + $("td.ingredient", this).text() + '",';
ing += '"Units": ' + $("td.units", this).text() + ',';
ing += '"Measure": "' + $("td.measure", this).text() + '"} ,';
}
cnt = cnt + 1;
});
alert(cnt);
if (ing != "") {
jsontext += '"Ingredients": [';
ing = ing.substring(0, jsontext.length - 1);
jsontext = jsontext + ing;
jsontext += ']';
}
jsontext += '}';
var json = eval('(' + jsontext + ')');
//var json = { Field: 1 };
$.ajax({
url: "/Recipe/Save",
type: "POST",
dataType: 'json',
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
success: function () {
//alert("DONE!!");
}
});
});
[/code]
I would recommend a refactoring of your javascript as it would help you identify the errors more easily. Also checkout with FireBug the actual JSON request being sent to the controller:
$("#Save").click(function () {
var ingredients = $('#ingredients tr.ingredientdata').map(function(index, element) {
return {
ingredientName: $('td.ingredient', element).text(),
units: $('td.units', element).text(),
measure: $('td.measure', element).text()
};
});
var json = {
RecipeTitle: $('#recipetitle').val(),
CategoryID: $('#category').val(),
PrepTime: $('#prepTime').val(),
PrepTimePeriod: $('#lstPrepTime').val(),
CookTime: $('#cookTime').val(),
CookTimePeriod: $('#lstCookTime').val(),
Rating: $('#rating').val(),
Method: $('#method').val(),
Ingredients: ingredients
};
$.ajax({
url: '/Recipe/Save',
type: 'POST',
dataType: 'json',
data: JSON.stringify(json),
contentType: 'application/json; charset=utf-8',
success: function () {
//alert("DONE!!");
}
});
});