Ionic alert - check if result is undefined - javascript

I load a JSON file from a server with angular and Ionic.
This is my code:
$scope.showAlert = function(mo,di,mi,don,fr,sa,so) {
$ionicPopup.alert({
title: 'Success',
content: mo + "<br>" + di + "<br>" + mi + "<br>" + don + "<br>" + fr + "<br>" + sa+ "<br>" + so
}).then(function(res) {
console.log('Test Alert Box');
});
};
For the Item:
<i class="icon ion-ios-clock-outline links" ng-click="showAlert(item.openingHours[0], item.openingHours[1], item.openingHours[2], item.openingHours[3],
item.openingHours[4], item.openingHours[5], item.openingHours[6]
)"></i>
My Problem is that sometimes the results, for example item.openingHours[6] is undefined. I don't want a undefined text in my alert. How can I check if the value is undefined in the alert?

Use conditional (ternary) operator ?, to check that str is defined, if defined return the value with br, if not - empty string:
$scope.showAlert = function(mo, di, mi, don, fr, sa, so) {
function getStrWithBr(str) {
return str ? str + '<br/>' : '';
}
var content =
getStrWithBr(mo) +
getStrWithBr(di) +
getStrWithBr(mi) +
getStrWithBr(fr) +
getStrWithBr(sa) +
so || '';
...

Related

How to make variables optional while concatenation of string?

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 ..
}

Uncaught syntaxerror: Unexpected Identifier (Javascript, asp.net mvc, cshtml)

So the error I am receiving is when I click the remove button on the dynamically created html, which is meant to call the remove method at the bottom and pass the arguments. The passing of the object as an argument is where I am running into the problems..
function addMarkerToList(args) {
var object = args;
var camera = args.id;
var test = selectedCameras.indexOf(args.id);
var noOfCamerasAllowed = #Model.usersName.CamerasSelectable;
if (selectedCameras.length < noOfCamerasAllowed) {
if (test > -1) {
alert("Camera already in list");
} else
{
selectedCameras.push(args.id);
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
//$("#cameraSelectedList").append("<p id=" + args.id + ">" + args.id + "</p>");
$("#cameraSelectedList").append(
"<div id = " + camera + " class=\"col-md-12\">" +
"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 user-item\">" +
"<div class=\"user-container\">" +
"<a class=\"user-avatar\"><i class=\"glyphicon glyphicon-facetime-video\" style=\"color: #ed1c24; font-size: 36px;\"></i></a>" +
"<p class=\"user-name\">" +
"<span>Camera</span>" +
This is where I think the issue is being caused:
"<input type=\"button\" value=\"Remove\" onclick=\"removeMarkerFromList(" + object + ")\"/>" +
"</p>" +
"</div>" +
"</div>");
The directly above section is where the error is being caused, I think by how I am passing the args called (object) in the input button back the the remove method below..
if (check === 0) {
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
} else {
//alert("This is the last added id: " + lastAddedId);
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 0;
lastAddedId = (camera + ".2");
}
}
} else {
alert("You have added the maximum number of cameras");
}
}
//Removing objects by right clicking the marker
function removeMarkerFromList(args) {
var camera = args.id;
alert(camera);
var test = selectedCameras.indexOf(camera);
if (test > -1) {
document.getElementById(camera).remove();
selectedCameras.splice(test, 1);
alert("Camera removed from list");
} else {
alert("Camera not in list");
}
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
}
You're concatenating your object into a string, which probably gives you something like
onclick="removeMarkerFromList([Object object])"
You can use an id (string or number) instead and retrieve your object afterwards:
"onclick=\"removeMarkerFromList(" + object.id + ")\"/>"
You can also stringify your object:
"onclick=\"removeMarkerFromList(" + JSON.stringify(object) + ")\"/>"
I managed to solve the issue by using object manipulation before passing the object to my method.
Thank you everyone for your assistance!
In ASP.NET/MVC/.NET Core project if you are facing this issue, sometimes this might be due to cache storage refresh not happening. In my instance, I had a Redis server running and it needed a manual restart. Go to Task Manager-> Services tab and see the server you are running and restart it manually( Redis server: Memurai in case if you are using windows).

Issue trying to escape a string in javascript plugin

I'm trying to use a Bootstrap Tab plugin for CKEditor, and it works well. But, when i use a single quote on content (doesn't matter if the string is "'", or " or '), it broke up.
I guess is just a escape issue. I tried with escape() and encodeURI(), but fails.
Error: SyntaxError: missing ) after argument list;
Source:
x)PRE3015 Pino 1/2'' 15mm Ponta Balistica Aço 3,1 15
The piece of plugin code for tabs is:
data: function() {
var bootstrapTab_d = new Date();
var bootstrapTab_id = bootstrapTab_d.getTime();
var bootstrapTab_item = bootstrapTab_contents = '';
for (var bootstrapTab_i = 0; bootstrapTab_i <= this.data.bootstrapTab_total; bootstrapTab_i++) {
eval("bootstrapTab_title = this.data.bootstrapTab_item" + bootstrapTab_i);
bootstrapTab_title = bootstrapTab_title != undefined ? bootstrapTab_title : '';
eval("bootstrapTab_content = this.data.bootstrapTab_content" + bootstrapTab_i);
bootstrapTab_content = bootstrapTab_content != undefined ? bootstrapTab_content : '';
eval("bootstrapTab_itemClass = this.data.bootstrapTab_itemClass" + bootstrapTab_i);
bootstrapTab_itemClass = bootstrapTab_itemClass != undefined ? bootstrapTab_itemClass : '';
eval("bootstrapTab_contentClass = this.data.bootstrapTab_contentClass" + bootstrapTab_i);
bootstrapTab_contentClass = bootstrapTab_contentClass != undefined ? bootstrapTab_contentClass : '';
if (bootstrapTab_title) {
bootstrapTab_item += '<li role="presentation" class="' + bootstrapTab_itemClass + '">' + bootstrapTab_title + '</li>';
bootstrapTab_contents += '<div role="tabpanel" class="' + bootstrapTab_contentClass + '" id="tab' + bootstrapTab_id + '_' + (bootstrapTab_i + 1) + '">' + bootstrapTab_content + '</div>'
}
}
this.element.setAttribute('id', 'collapse' + bootstrapTab_id);
this.element.$.innerHTML = '<div role="tabpanel"><ul class="nav nav-tabs" role="tablist">' + bootstrapTab_item + '</ul><div class="tab-content">' + bootstrapTab_contents + '</div></div>'
}
I'd refactor the code, and not use eval!
eval is evil http://blogs.msdn.com/b/ericlippert/archive/2003/11/01/53329.aspx
instead of
eval("bootstrapTab_title = this.data.bootstrapTab_item" + bootstrapTab_i);
use bootstrapTab_item as an array and do this
bootstrapTab_title = this.data.bootstrapTab_item[bootstrapTab_i]
really don't know if the error is there, but I think the path to find the error is refactor to eliminate those eval, that could be the source of your problem.

Using jQuery to rearrange page elements

I'm relatively new to jQuery and JavaScript, and I think I understand what is causing my issue, but I'm not sure how to fix it.
I'm using SimpleWeather.JS , moment.js, and moment.js timezone to get the current time and weather for 4 cities. I have all the data I want on the page, but I want to move each city's time as the second paragraph in each city's div. Any ideas on how to get that working with my current code or is there a more efficient way of producing this result?
http://jsfiddle.net/ljd144/p6tpvz1r/
Here's my JS:
$(document).ready(function () {
$('.weather').each(function () {
var city = $(this).attr("city");
var woeid = $(this).attr("woeid");
var degrees = $(this).attr("degrees");
var continent = $(this).attr("continent");
$.simpleWeather({
zipcode: '',
woeid: woeid,
location: '',
unit: degrees,
success: function (weather) {
if (continent == 'America'){
html = '<p>' + weather.city + ', ' + weather.region + '</p>';
}
else {
html = '<p>' + weather.city + ', ' + weather.country + '</p>';
}
//html += '<p class="time" id="'+city+'></p>';
//html += '<p>' + weather.updated + '</p>';
html += '<p><i class="icon-' + weather.code + '"></i> ' + weather.temp + '°' + weather.units.temp + '<p>';
html += '<p>' + weather.currently + '<p>';
$('#weather_' + city).html(html);
},
error: function (error) {
$('#weather_' + city).html('<p>' + error + '</p>');
}
});
});
$(function () {
setInterval(function () {
$('.time').each(function () {
var city = $(this).attr("city");
var continent = $(this).attr("continent");
//$(this).text(city);
var utc = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(utc).toDate();
cityTime = moment(localTime).tz(continent + "/" + city).format('ddd MMM D YYYY, h:mm:ss a z');
$(this).text(city+ ': '+cityTime);
});
}, 1000);
});
$('.time').each(function () {
var city = $(this).attr("city");
//$('#weather_' + city).after(this);
});
});
You can use appendTo() method to append the time to the respective <div> having same city attribute using the attribute equals selector like:
$(this).text(city + ': ' + cityTime).appendTo("div[city='"+city+"']");
Updated fiddle
DEMO
Change:
$(this).text(city+ ': '+cityTime);
To:
var timeP = $('p.time','#weather_' + city);
timeP = timeP.length ? timeP : $('<p/>',{class:'time'}).appendTo( '#weather_' + city );
timeP.text(cityTime);

Adding javascript loops into SQL database

What i am trying to achieve is adding the javascript loops and the named variables into an sql database, some of them are already added to an external script so work fine however some which i have named in the SQL script at the bottom still need adding, however as the database won't accept a colon ":" they won't enter it and is returning an error, looking at the code at the bottom with replace function im sure you can see what i am trying to achieve but failing miserably, help is much appreciated!
window.status = 'Loading contingency scripts - please wait...';
audit('Loading contingency scripts');
var conting = {
i: 0,
start: function() {
window.status = 'Loading form - please wait...';
var t = '';
t += '<form name="frm_conting" id="frm_conting" onsubmit="return false;">';
t += '<table width="100%" cellspacing="1" cellpadding="0">';
t += '<tr><td>Date (DD/MM/YY):</td><td><input type="text" size="8" value="' + current_date + '" id="date"></td></tr>';
t += '<tr><td>Time Started:</td><td><select id="timefrom"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select></td></tr>';
t += '<tr><td>Time Finished:</td><td><select id="timeto"><option></option>';
for (h = 8; h < 23; h++) {
for (m = 0; m < 46; m = m + 15) {
t += '<option value=' + nb[h] + ':' + nb[m] + '>' + nb[h] + ':' + nb[m] + '</option>';
};
};
t += '</select><tr><td>Extension #:</td><td><input type="text" size="5" value="' + my.extension + '" id="staffid"></td></tr>';
t += '<tr><td>Desk ID:</td><td><input type="text" size="5" value=' + my.deskid + ' id="desk"></td></tr>';
t += '<tr><td>Number of calls:</td><td><input type="text" size="5" id="calls"></td></tr>';
t += '<tr><td>Avid ID:</td><td><input type="text" size="5" id="avid"></td></tr>';
t += '<tr><td><input type="button" value="Submit" onClick="conting.save()"></td>';
t += '</table>';
t += '</form>';
div_form.innerHTML = t;
window.resizeTo(400, 385);
window.status = '';
},
save: function() {
var conting_date = frm_conting.date.value;
if (!isdate(conting_date)) {
alert("You have entered an incorrect date.");
return false;
};
var conting_timefrom = frm_conting.timefrom.value;
var conting_timeto = frm_conting.timeto.value;
if (conting_timefrom == '' || conting_timeto == '') {
alert("You need to enter a starting & finishing time.");
return false;
};
if (conting_timefrom > conting_timeto) {
alert("The time you have entered is after the finish time.");
return false;
};
var conting_staffid = frm_conting.staffid.value;
if (conting_staffid.length != 5) {
alert("You have entered an incorrect extension number.");
return false;
};
var conting_desk = frm_conting.desk.value;
if (conting_desk.length != 5) {
alert("You have entered an incorrect desk ID.");
return false;
};
var conting_calls = frm_conting.calls.value;
if (isNaN(conting_calls)) {
alert("You have not entered amount of calls.");
return false;
};
var conting_avid = frm_conting.avid.value;
if (isNaN(conting_avid)) {
alert("You have entered an incorrect avid ID.");
return false;
};
if (conting_avid.length != 5) {
alert("You have entered an incorrect avid ID.");
return false;
};
conn.open(db["contingency"]);
rs.open("SELECT MAX(prac_id) FROM practice", conn);
var prac_id = rs.fields(0).value + 1;
var prac_timefrom = parseFloat(frm_conting.timefrom.value);
var prac_timeto = parseFloat(frm_conting.timefrom.value);
var prac_calls = frm_conting.calls.value;
var prac_avid = frm_conting.avid.value;
rs.close();
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
conn.close();
}
};
window.status = '';​
This bit of code looks extremely dubious.
var q = "INSERT INTO practice (prac_id, prac_staffid, prac_date, prac_timefrom, prac_timeto, prac_extension, prac_desk, prac_calls, prac_avid) VALUES (" + prac_id + "," + my.id + ", " + current_date + ", " + prac_timefrom + ", " + prac_timeto + ", " + my.extension + ", " + my.deskid + ", " + prac_calls + ", " + prac_avid + ")";
var q = "UPDATE SELECT practice REPLACE ('isNaN', ':', 'isNull')"
alert(prac_timefrom);
rs.open(q, conn);
you should use parameterised queries to avoid SQL injection. Additionally even without any deliberate SQL injection attempts this code will fail if any of the form fields contain the ' character.
You are assigning to the variable q twice and aren't executing the result of the first assignment. (And declaring it twice actually?!)
There is no syntax such as UPDATE SELECT it would need to be something like UPDATE practice SET SomeColumn = REPLACE (SomeColumn, 'isNaN', 'isNull') presumably except see 4 and 5.
I'm not clear what the Replace is meant to be doing anyway. What are the 3 parameters you have given it?
It would be better to do the Replace on the value before inserting into the database rather than inserting it wrong then updating it to the new value.

Categories

Resources