Can't get json object - javascript

I am trying to get city name from input element and then get the weather information and also timezone information of the city from API.
However i can't get the json object in that function but it works outside the function.
Can anyone help me?
var d = "Lisbon";
$(document).ready(function() {
$("#button").click(function() {
d = document.getElementById("input").value;
$(document).ready(function myfunction() {
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
document.getElementById("city").innerHTML = data.name + ", " + data.sys.country;
document.getElementById("wind").innerHTML = data.wind.speed + " m/s ";
document.getElementById("cloudiness").innerHTML = data.weather[0].description;
document.getElementById("pressure").innerHTML = data.main.pressure + " hpa";
document.getElementById("humidity").innerHTML = data.main.humidity + " %";
document.getElementById("coord").innerHTML = "[ " + data.coord.lat + ", " + data.coord.lon + " ]";
document.getElementById("temperature").innerHTML = data.main.temp + "°C";
document.getElementById("icon").innerHTML = "<img src=http://openweathermap.org/img/w/" + data.weather[0].icon + ".png" + ">";
console.log(data);
(function() {
$.getJSON("http://api.geonames.org/timezoneJSON?" + "lat=" + data.coord.lat + "&" + "lng=" + data.coord.lon + "&username=hrrs", function(data) {
document.getElementById("time").innerHTML = data.time;
document.getElementById("timeCity").innerHTML = data.timezoneId;
document.getElementById("country").innerHTML = data.countryName;
document.getElementById("sunrise").innerHTML = data.sunrise;
document.getElementById("sunset").innerHTML = data.sunset;
console.log(data);
});
})();
});
document.getElementById("slayt").innerHTML = '<iframe src="http://www.panoramio.com/wapi/template/slideshow.html?tag=' + d + '&width=1920&height=500&" frameborder="0" width="1920" height="500" scrolling="no" marginwidth="0" marginheight="0"></iframe>';
})();
});
});

Is this what you are trying to achieve?
http://jsfiddle.net/wnunhhac/
<input type="text" id="inputCity" value="Zurich"/>
<input type="button" id="start" value="Go" />
<br />
<span id="city">click go</span>
$(document).ready(function() {
$("#start").click(function() {
var d = $("#inputCity").val();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?APPID=11d324c05e02e308c1c9eb8d8041b143&q=' + d + '&units=metric', function(data) {
$("#city").html(data.name);
});
});
});
The API returns status code 404 not found, if the city is invalid. So you should code an appropriate resonse.
if (data.cod === "404") {
// Api could not find city
return;
}
Also I changed the button type to "button" instead of "submit"
<button type="button" id="button" class="btn btn-default">
Corresponding Fiddle: http://jsfiddle.net/xvn6f05w/

Related

Update status while Drag and drop in sharepoint list

I have Using Nestable js to drag and drop my list items .and the drag and drop is working fine in UI .but what i need is ,I want to update the status of list items after the item is dropped..How can i achieve this using javascript..
for reference of Nestable js https://codepen.io/Mestika/pen/vNpvVw
Next am retrieving the list items like bellow code
var ListEnumerator = this.myItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
var status = currentItem.get_item('Status');
if (status == "Planned") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridprocess').append(templateString);
}
else if (status == "In Process") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridinprogress').append(templateString);
}
else if (status == "Completed") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridcomplete').append(templateString);
}
else if (status == "Hold") {
var templateString = '<li class="dd-item" ref="' + currentItem.get_item('ID') + '"><div class="dd-handle"><h6>' + currentItem.get_item('Title') + '</h6><span class="time"><strong>Start: ' + new Date(currentItem.get_item('PlanStart')).toDateString() + '</strong><br/><strong>End: ' + new Date(currentItem.get_item('PlanEnd')).toDateString() + '</strong></span><p>' + currentItem.get_item('TaskDescription') + '</p><strong>Assigned To :</strong><p>' + currentItem.get_item('AssignedTo').get_lookupValue() + '</p></div></li>';
$('#gridincomplete').append(templateString);
}
}
here the li tag is used under
<div class="dd">
<ol class="dd-list" id="gridprocess" >
</ol>
</div>
how can i update the status while drag and drop? please give the code to do it..
Finally I achieved the above question . with the following code...... first i have set on ID to the class name dd as ddprocess like bellow
<div class="dd" id="ddprocess">
<ol class="dd-list" id="gridprocess">
</ol>
</div>
And Next I have Write a function When the id ddprocess is on change i get the Each item id and pass the ID to the Update function
$('#ddprocess').on('change', function () {
// JSON To get the list item in Process
var $this = $(this);
var serializedData = window.JSON.stringify($($this).nestable('serialize'));
// console.log("sData:", serializedData)
// convert the JSON into Object
var obj = JSON.parse(serializedData);
obj.forEach(myFunction);
function myFunction(item, index) {
var eachid = item.id;
// console.log("Item-id", eachid);//you will get id
Updatetoprocess(eachid);
}
});
Next the update function is to Update the status to planned for each item in the ddprocess id .....
function Updatetoprocess(eachid) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
var siteurl = "https://abb.sharepoint.com/sites/IAPI-SOP";
var context = new SP.ClientContext(siteurl);
var olistnew = context.get_web().get_lists().getByTitle("TaskList");
var listitem = olistnew.getItemById(eachid);
listitem.set_item('Status', 'Planned');
listitem.update();
context.load(listitem);
context.executeQueryAsync(function () {
alert("Items Updated successfully");
},
function () { console.log("failure") }
)
});
}
Thank you

What is the simplest way to find the XML node position of a value?

I want to find the XML node position of stateInput
For example, if I select the state "Alabama" from the datalist I want my code to return the XML node position of "Alabama" so that related attributes such as "population" can also be retrieved in the results.
What is the simplest solution to this problem?
Note: in this test, I manually set the node position variable = 2. Currently, regardless of the selected state, Node position of state input = 2, State node = California, etc. That's only a correct match if California is selected.
var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function testResults() {
document.getElementById("stateInput").innerHTML = myInputId.value;
}
var parser, xmlDoc, x, i;
var text =
"<STATE_DATA>" +
"<UNIT>" +
"<STATE>Wisconsin</STATE>"+
"<GDP>232,300,000,000</GDP>"+
"<POPULATION>5,800,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Alabama</STATE>" +
"<GDP>165,800,000,000</GDP>" +
"<POPULATION>4,900,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>California</STATE>" +
"<GDP>2,500,000,000,000</GDP>" +
"<POPULATION>39,600,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Texas</STATE>" +
"<GDP>1,600,000,000,000</GDP>" +
"<POPULATION>28,300,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Michigan</STATE>" +
"<GDP>382,000,000</GDP>" +
"<POPULATION>10,000,000</POPULATION>" +
"</UNIT>" +
"</STATE_DATA>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
var a = 2; /*I want: var a = XML node position of stateInput*/
document.getElementById("stateNodePosition").innerHTML = a;
document.getElementById("stateNode").innerHTML =
xmlDoc.getElementsByTagName("STATE")[a].childNodes[0].nodeValue;
document.getElementById("populationNode").innerHTML =
xmlDoc.getElementsByTagName("POPULATION")[a].childNodes[0].nodeValue;
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="testResults()">submit</button>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>
<p>State input: <span id="stateInput"></span></p>
<p>Node position of state input: <span id="stateNodePosition"></span></p>
<p>State node: <span id="stateNode"></span></p>
<p>Population node: <span id="populationNode"></span></p>
Iterate through all STATEs and find the one whose textContent is the state you want, and then you can access its parent to get to its UNIT. The only changes are in testResults:
var n = document.getElementById("myInputId");
n.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById("myButton").click();
}
});
function testResults() {
const { value } = myInputId;
const foundState = [...xmlDoc.querySelectorAll('STATE')]
.find(possibleMatch => possibleMatch.textContent === value);
const unit = foundState.parentElement;
console.log(unit.innerHTML);
document.getElementById("stateInput").innerHTML = value + ' has pop ' + unit.children[2].textContent;
}
var parser, xmlDoc, x, i;
var text =
"<STATE_DATA>" +
"<UNIT>" +
"<STATE>Wisconsin</STATE>" +
"<GDP>232,300,000,000</GDP>" +
"<POPULATION>5,800,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Alabama</STATE>" +
"<GDP>165,800,000,000</GDP>" +
"<POPULATION>4,900,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>California</STATE>" +
"<GDP>2,500,000,000,000</GDP>" +
"<POPULATION>39,600,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Texas</STATE>" +
"<GDP>1,600,000,000,000</GDP>" +
"<POPULATION>28,300,000</POPULATION>" +
"</UNIT>" +
"<UNIT>" +
"<STATE>Michigan</STATE>" +
"<GDP>382,000,000</GDP>" +
"<POPULATION>10,000,000</POPULATION>" +
"</UNIT>" +
"</STATE_DATA>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
var a = 2; /*I want: var a = XML node position of stateInput*/
document.getElementById("stateNodePosition").innerHTML = a;
document.getElementById("stateNode").innerHTML =
xmlDoc.getElementsByTagName("STATE")[a].childNodes[0].nodeValue;
document.getElementById("populationNode").innerHTML =
xmlDoc.getElementsByTagName("POPULATION")[a].childNodes[0].nodeValue;
<input list="myInput" id="myInputId" value="">
<button id="myButton" onClick="testResults()">submit</button>
<datalist id="myInput">
<option id="AL">Alabama</option>
<option id="CA">California</option>
<option id="MI">Michigan</option>
<option id="TX">Texas</option>
<option id="WI">Wisconsin</option>
</datalist>
<p>State input: <span id="stateInput"></span></p>
<p>Node position of state input: <span id="stateNodePosition"></span></p>
<p>State node: <span id="stateNode"></span></p>
<p>Population node: <span id="populationNode"></span></p>

JavaScript Syntax error

I have two functions in JavaScript and get the following error:
Uncaught SyntaxError: missing ) after argument list
It is not giving me a line number and I can't seem to find the culprit; would appreciate any assistance:
function makeRequest() {
var xmlhttp = new XMLHttpRequest();
console.log('reached');
xmlhttp.onreadystatechange = function() //This part is actually executed last
{
console.log("within");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) // Was the request processed successfully?
{
console.log(location);
console.log(xmlhttp.responseText);
first = xmlhttp.responseText.substring(xmlhttp.responseText
.search('first:') + 6, xmlhttp.responseText
.search(',last'));
console.log("First: " + first);
last = xmlhttp.responseText.substring(xmlhttp.responseText
.search(',last') + 6, xmlhttp.responseText
.search(',utt'));
console.log("last: " + last);
utt = xmlhttp.responseText.substring(xmlhttp.responseText
.search(',utt') + 5, xmlhttp.responseText
.search(',type'));
console.log("utt: " + utt);
type = "";
attribute = "";
out = "";
index = "";
values = "";
if (xmlhttp.responseText.search(',att') > -1) {
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
//attribute
pass = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
} else {
type = 'instance';
//index
pass = xmlhttp.responseText
.substring(xmlhttp.responseText
.search('indexResult:') + 12,
xmlhttp.responseText.search(',inst:'));
out = xmlhttp.responseText.substring(
xmlhttp.responseText.search('inst:') + 5,
xmlhttp.responseText.search('}'));
}
console.log("type: " + type);
if (type === 'attribute') {
vals = values.split(",");
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this; what would be your preferred "
+ attribute.toLowerCase().substring(0,
attribute.length - 1)
+ "&#63</br></br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option>";
for (i = 0; i < vals.length; i++) {
html = html + "<option value='"+vals[i]+"'>"
+ vals[i] + "</option>";
}
html = html
+ "</select></br></br><input type='button' onclick='return sendChoice("
+ first + "," + last + "," + utt + "," + type
+ "," + pass + ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
if (type === 'instance') {
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this; </br> "
+ out
+ "</br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option><option value='yes'>yes</option><option value='no'>no</option></select></br></br><input type='button' onclick='return sendChoice("
+ first
+ ","
+ last
+ ","
+ utt
+ ","
+ type
+ "," + pass + ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
}
}
console
.log("http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet?first="
+ first + "&last=" + last);
xmlhttp
.open(
"Get",
"http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet?first="
+ first + "&last=" + last, true);
console.log('before');
xmlhttp.send();
console.log('after');
}
and the other function is:
function sendChoice(fname, lname, utterance, type, pass) {
if (document.getElementById('choice').value === 'makeSelection') {
alert('please make a choice');
return false;
}
else {
choice = document.getElementById('choice').value;
first = fname;
last = lname;
utt = utterance;
typ = type;
attOrInstIndex = pass;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() //This part is actually executed last
{
console.log("within");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) // Was the request processed successfully?
{
console.log(location);
console.log(xmlhttp.responseText);
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
attribute = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
vals = values.split(",");
console.log("type: " + type);
if (xmlhttp.responseText.search(',att') > -1) {
type = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',type') + 6,
xmlhttp.responseText.search(',att'));
//attribute
pass = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',att') + 5,
xmlhttp.responseText.search(',vals'));
values = xmlhttp.responseText.substring(
xmlhttp.responseText.search(',vals') + 7,
xmlhttp.responseText.search(']}'));
} else if (xmlhttp.responseText.search('instance') > -1) {
type = 'instance';
//index
pass = xmlhttp.responseText
.substring(xmlhttp.responseText
.search('indexResult:') + 12,
xmlhttp.responseText
.search(',inst:'));
out = xmlhttp.responseText.substring(
xmlhttp.responseText.search('inst:') + 5,
xmlhttp.responseText.search('}'));
} else {
type = 'done';
}
if (type === 'attribute') {
vals = values.split(",");
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this and the choices you have made so far; what would be your preferred "
+ attribute.toLowerCase().substring(0,
attribute.length - 1)
+ "?</br></br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option>";
for (i = 0; i < vals.length; i++) {
html = html + "<option value='"+vals[i]+"'>"
+ vals[i] + "</option>";
}
html = html
+ "</select></br></br><input type='button' onclick='return sendChoice("
+ first + "," + last + "," + utt + ","
+ type + "," + pass
+ ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
}
if (type === 'instance') {
html = "You have said the following to the virtual assistant: </br><i>'"
+ utt
+ "'</i></br></br>Given that you have said this and the choices you have made so far; </br> "
+ out
+ "</br><select id='choice' name='attribute'><option selected='selected' value='makeSelection'>please choose</option><option value='yes'>yes</option><option value='no'>no</option></select></br></br><input type='button' onclick='return sendChoice("
+ first
+ ","
+ last
+ ","
+ utt
+ ","
+ type
+ ","
+ pass
+ ")' value='Submit'></input>";
document.getElementById("utteranceDiv").innerHTML = html;
} else {
//done make final Page.
html = "Thank you this scenario is over.";
document.getElementById("utteranceDiv").innerHTML = html;
}
}
}
xmlhttp
.open(
"Post",
"http://"
+ server
+ "/DialogueRefinementWebExperiment/WebExperimentServlet",
true);
//xmlhttp.setRequestHeader("accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
console.log('before');
if (typ == "attribute") {
xmlhttp.send("first=" + first + "&last=" + last
+ "&mainType=" + type + "&att=" + attOrInstIndex
+ "&utt=" + utt + "&choice=" + choice + "&done=no");
} else if (typ == "instance") {
xmlhttp.send("first=" + first + "&last=" + last
+ "&mainType=" + type + "&indexResult="
+ attOrInstIndex + "&utt=" + utt + "&choice="
+ choice + "&done=" + choice);
}
}
}
The HTML is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
window.onload = function init() {
server = window.location.host;
params = location.search.split("?")[1];
first = params.split("&")[0].split("=")[1];
last = params.split("&")[1].split("=")[1];
}
</script>
</head>
<body>
<div id="utteranceDiv">
When you are ready click Submit and the system will begin to ask you
questions in an attempt to find you a restaurant that you are happy
with.</br> <input type="button" onclick="return makeRequest()"
value="Select"></input>
</div>
<script type="text/javascript">
//see above for javascipt
</script>
</body>
</html>
the div gets updated after the first call:
<div id="utteranceDiv">
You have said the following to the virtual assistant: <br><i>'i want a
mexican restaurant at 7 pm in cupertino'
</i><br><br>Given that you have said this; <br> How about null. It is in
Mountain View; in Peninsula. There is a reservation at earlyNight.<br>
<select id="choice" name="attribute"><option selected="selected"
value="makeSelection">please choose</option>
<option value="yes">yes</option>
<option value="no">no</option></select><br><br><input type="button"
onclick="return sendChoice(eli,pincus,i want a mexican restaurant at 7 pm in
cupertino,instance,1)" value="Submit"></div>
I check your post, but i cant find any missing ")". The console doesnt tell you where to look?
I figured it out; it is because the arguments of the javascript function that get written on the updated page are strings and so need qoutes around them (one of them had spaces and thats why i didn't get a line number it messes up the parser)

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