Phonegap - inserting variable into database - javascript

I'm trying to insert variables values to a data base but it comes out as 'undefined'.
It is all inside device ready. I'm testing 1st with the variable 'absenceDateFrom'.
var absenceType = document.getElementById('absenceType')
var absenceText = document.getElementById('noteNewAbsence')
var absenceDateFrom = document.getElementById('absenceFrom')
var absenceDateTo = document.getElementById('absenceTo')
db.transaction(
function(tx) {
tx.executeSql("INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES (" + id++
+ ",'"
+ String(absenceType.value)
+ "','"
+ absenceDateFrom.value.toString
+ "','"
+ absenceDateTo.value.toString
+ "','"
+ "random note (this works but if i put absenceText.value it comes out undefined also"
+ "',"
+ "'true'"
+ ","
+ "'image.jpg'"
+ ")");
}, transaction_error);
I also tried with '?' and [absenceDateFrom] in the end, like I saw on another answer and it still comes out undefined:
var absenceType = document.getElementById('absenceType')
var absenceText = document.getElementById('noteNewAbsence')
var absenceDateFrom = document.getElementById('absenceFrom')
var absenceDateTo = document.getElementById('absenceTo')
db.transaction(
function(tx) {
tx.executeSql("INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES (" + id++
+ ",'"
+ String(absenceType.value)
+ "',"
+ "?"
+ ",'"
+ absenceDateTo.value.toString
+ "','"
+ "random note (this works but if i put absenceText.value it comes out undefined also"
+ "',"
+ "'true'"
+ ","
+ "'image.jpg'"
+ ")", [absenceDateFrom.value] );
}, transaction_error);
output:
http://prntscr.com/44eb31

Following is the assumptions that I have made about datatypes of the variables.
Number id;
String type,absenceFrom,absenceTo,note,aproved,picture;
Also aproved variable seems to be typo error. Should it not be approved
I have modified your tx() call
If there are any errors in the insert call. check the output of the errorInsert call
db.transaction(
function(tx) {
var sqlStmt = "INSERT INTO absences (id,type,absenceFrom,absenceTo,note,aproved,picture) VALUES ("
+ (id++) + ","
+ "'" + String(type) + "',"
+ "'" + String(absenceDateFrom) + "',"
+ "'" + String(absenceDateTo) + "',"
+ "'" + "random note (this works but if i put absenceText.value it comes out undefined also" + "',"
+ "'" + "true" + "',"
+ "'" + "image.jpg" + "',"
+ ")";
console.log("sqlStmt:"+sqlStmt);
tx.executeSql(sqlStmt,successInsert,errorInsert);
function errorInsert (err) {
console.log("ERROR CODE:"+err.code+":Message:"+err.message);
}
function successInsert(tx, result) {
console.log("SuccessInsert():Last inserted ID = " + result.insertId);
console.log("SuccessInsert():rowsAffected: " + result.rowsAffected);
}
}, transaction_error);

First: try to console.log(absenceDateTo) before inserting and be sure that the value is not undefined.
Second: In the line :
absenceDateTo.value.toString
You are passing the function context but you should call the function instead.
absenceDateTo.value.toString()
Try this ;)

Related

I'm trying to get first 3 results from MySQL database in Node.js and I'm getting this error

Here's the code I'm using
con.query('SELECT * FROM tables', function(err, results) {
if (err) throw err
console.log(results[0].rawname)
for(var i= 0; i <= 3; i++) {
eval("var " + 'name_' + i + ' = ' + "'" + results[i].rawname + "'" + ";")
eval("var " + 'url_' + i + ' = ' + "'" + results[i].url + "'" + ";")
eval("var " + 'creator_' + i + ' = ' + "'" + results[i].creator + "'" + ';' )
}
I'm getting this error:
TypeError: Cannot read property 'rawname' of undefined
Now I know it's a problem with the i variable since I tried logging it outside the loop with a 0 in the place of the i and it seems to work fine, how can I do it with the i variable?
You are counting from zero till 3 included. So you try to loop over 4 results instead of the intended 3 results.
so the problem was not in the js but in the table, so the thing is there was no results[1] since i only had 1 result, well, sorry for wasting your time.

Uncaught SyntaxError: Unexpected identifier error at a single quote in webview

I am passing certain values to a form which is loaded on webview to autofill it using JavaScript. It works perfectly till any one of the Strings passed has a single quote " ' " in it. When a single quote is encountered I get this error:
Uncaught SyntaxError: Unexpected identifier
And no data gets filled.
The code to autofill the form
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
PageURL = view.getUrl();
PageTitle = view.getTitle();
actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(PageTitle);
}
actionBar.setSubtitle(PageURL);
final String js = "javascript: " +
"var nameDoc = document.getElementsByName('name');" +
"nameDoc[0].value = '" + n + "';" +
"var checkOutDoc = document.getElementsByName('checkout');" +
"checkOutDoc[0].value = '" + btn_co + "';" +
"var noOFPaxDoc = document.getElementsByName('no_of_pax');" +
"noOFPaxDoc[0].value = '" + a + "';" + // a should be int based on ur HTML
"var noOFKidDoc = document.getElementsByName('no_of_kid');" +
"noOFKidDoc[0].value = '" + k + "';" + // a should be int based on ur HTML
"var noOFRoomsDoc = document.getElementsByName('no_of_rooms');" +
"noOFRoomsDoc[0].value = '" + r + "';" + // a should be int based on ur HTML
"var checkInDoc = document.getElementsByName('checkin');" +
"checkInDoc[0].value = '" + btn_ci + "';" +
"var email = document.getElementsByName('guest_email');" +
"email[0].value = '" + m + "';" +
"var resortName = document.getElementsByName('resort_name[]');" +
"resortName[0].value = '" + mail_list[0] + "';" +
"var distFrom = document.getElementsByName('distance_from[]');" +
"distFrom[0].value = '" + dist + "';" +
"var roomType = document.getElementsByName('room_category[]');" +
"roomType[0].value = '" + room_list[0] + "';" +
"var price = document.getElementsByName('package_price[]');" +
"price[0].value = '" + room_price_list[0] + "';" +
"var distance = document.getElementsByName('distance[]');" +
"distance[0].value = '" + distance + "';" +
"var ex = document.getElementsByName('excursions[]');" +
"ex[0].value = '" + ex + "';" +
"var act = document.getElementsByName('activities[]');" +
"act[0].value = '" + act_f + "';" +
"var dest = document.getElementsByName('destination');" +
"dest[0].value = '" + state + "';" +
"var days = document.getElementsByName('total_days');" +
"days[0].value = '" + d + "';" +
"javascript:(function(){" +
"l=document.getElementsByName('submit');" +
"e=document.createEvent('HTMLEvents');" +
"e.initEvent('click',true,true);" +
"l[0].dispatchEvent(e);" +
"})()";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(js, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
}
});
} else {
view.loadUrl(js);
}
}
It happens because your strings are not escaped. When you insert data directly into JS as you're doing the computer doesn't know the difference between cod you entered and code that was added from the input field.
Thus, when your users input some text
nameDoc[0].value = '" + n + "';
becomes
nameDoc[0].value = 'My name is Norbs' and I'm breaking your code';
In the example above, the string is ended after "Norbs", and as what comes afterwards is not valid JS the script fails.
Possible solution
Change
nameDoc[0].value = '" + n + "';
To
nameDoc[0].value = '" + n.replace("'", "\'") + "';.

Javascript method argument escape

The below span tag containing an onclick event is not working
var test="<span onClick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />"
the above escaped string has some problems with the method call.
How can I fix it?
If you're creating this in JavaScript to create an element, then the first single-quote needs to be escaped.
function gotoNode(name, xaxis, yaxis, detail, status) {
alert("name = " + name + "\r\nxaxis = " + xaxis + "\r\nyaxis = " + yaxis + "\r\ndetail = " + detail + "\r\nstatus = " + status);
}
var result = { name: "name", xaxis: "xaxis", yaxis: "yaxis", detail: "detail", status: "status" };
var htmlText = '<input value="Button" type="button" onclick="gotoNode(\'' + result.name + '\',\'' + result.xaxis + '\',\'' + result.yaxis + '\',\'' + result.detail + '\',\'' + result.status + '\')" />';
$("#lonely").append(htmlText);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lonely"></div>
Generally speaking, whatever quote type you begin with (out of ' or "), you need to escape the same type that you want to use within the string and not escape the same type to terminate the string. You can leave the other type without escapes.
For your edited version, this should work if you want those result variables to be replaced with their values.
var test = "<span onclick=\"gotoNode('" + result.name + "','" + result.xaxis + "','" + result.yaxis + "','" + result.detail + "','" + result.status + "')\" />";
Do you use php to generate the output?
Then you should try
echo "<input type=\"button\" onClick=\"gotoNode(\" + result.name + \",\" +
result.xaxis + \",\" + result.yaxis + \",\" + result.detail + \",\" +
result.status + \")\" />";

onclick event and json data not meshing together

I've got a silly error which I cant seem to fix some how. I'm simply looking to do the following:
onclick="CreatePro('x','y','z')"
I basically want to pass text to the CreatePro function. Now my values of x,y and z are json data. As such here is what I am using for the javascript:
var Provision = "'" + data[i].ProvisionID + "'";
var Title = "'" + data[i].Title + "'";
var Author = "'" + data[i].Author + "'";
var Edition = "'" + data[i].Edition + "'";
var Publisher = "'" + data[i].Publisher+ "'";
var ISBN = "'" + data[i].ISBN + "'";
var UserID = "'" +data[i].UserID + "'";
var Price = "'" + data[i].Price+ "'";
var Condition = "'" +data[i].Condition +"'";
Row = Row + "<td><input type='button' onclick='CreatePro(" + Provision + "," + Title+ "," + Author + "," + Edition + "," + Publisher +"," + ISBN + ","+ UserID + ","+ Price + "," + Condition + ")' value='Create'></td></tr>";
console.log(Row);
Now when I use console.log I get the following:
<td><input type='button' onclick='CreatePro('19','dfjeryj','ertj','0','tj','0000000000000','4','0','0')' value='Create'></td>
But when I inspect the element I have :
<input type="button" onclick="CreatePro(" 19','dfjeryj','ertj','0','tj','0000000000000','4','0','0')'="" value="Create">
The problem is suspect is the " on the above line. But I dont know why this is happening? As from the console log. My quotes seem to match up. So I'm not sure why the browser is mixing them up? Perhaps I've gone wrong somewhere? (Frankly I can;t see the error). Every time I click the create button the event doesn't call my CreatePro function. I'm really not sure what I'm doing wrong or perhaps a better way of doing what I'm doing
You have got your quotes wrong. It should be:
Row = Row + "<td><input type='button' onclick=\"CreatePro('" + Provision + "','" + Title+ "','" + Author + "','" + Edition + "','" + Publisher +"','" + ISBN + "','"+ UserID + "','"+ Price + "','" + Condition + "')\" value='Create'></td></tr>";

Function in JavaScript that outputs concat url to YUI Chart Library Output

Trying to properly write a function in JavaScript that outputs a concat'd url to Chart Library Output (for chart re-rendering)... based on selected options in dropdown list.
Problem: I am not getting the chart to re-render with the concatenated url (which should be sent each time an option is selected in the dropdown).
JavaScript code in head:
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest(); // instantiate request
xmlHttp.open( "GET", theUrl, false ); // open url
xmlHttp.send( null ); // sending nothing
return xmlHttp.responseText; // return url's data as text
};
function selectFabric(){
var urlString = "http://localhost:8083/tbl/sparqlmotion?id=LiabilityChart&arg1=";
var fabrics = document.getElementById('fabrics');
var selectedFabric = fabrics.options[fabrics.selectedIndex];
var linkAddTogether = [urlString + selectedFabric.value];
var linkResult = linkAddTogether[0];
var result = httpGet(linkResult);
if (selectedFabric.value != "nothing"){
return linkResult; // update begins // document.write(linkAddTogether)
};
};
function revive (key, value) {
if (value.datatype == "http://www.w3.org/2001/XMLSchema#double" || // if datatype is this
value.datatype == "http://www.w3.org/2001/XMLSchema#integer" || // or, this
value.datatype == "http://www.w3.org/2001/XMLSchema#float") // or, this
{
return (parseInt(value.value)) // if '#double', '#integer', or '#schema', then: 'vars' label + convert the datatype's float value to integer
}
else if (value.type == 'literal')
{
return (value.value) // if datatype's value is a literal: 'vars' label + return as a string
}
else if (value.datatype == 'http://www.w3.org/2001/XMLSchema#date')
{
return value.value // if "XMLSchema#date's" value is a literal: 'vars' label + return as a string
}
else
{
return value // if datatype is anything else: 'vars' label + return value as a string
}
};
var scriptHead = ["YUI().use('charts',function(Y){var myDataValues=\n\n["];
var scriptTail = ["\n];\n\nvar styleDef={series:{Stock:{line:{color:'#EEB647'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Liability:{line:{color:'#171944'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#222',alpha:0,wmode:'transparent'},over:{fill:{color:'#eee'},border:{color:'#000'},width:9,height:9}}},Shipment:{line:{color:'#ff0000',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#ff0000',alpha:0,wmode:'transparent'},over:{fill:{color:'#ff0000',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Production:{line:{color:'#FFD700',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#FFD700',alpha:0,wmode:'transparent'},over:{fill:{color:'#FFD700',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}},Order:{line:{color:'#006400',alpha:0,wmode:'transparent'},marker:{fill:{color:'#eee',alpha:0,wmode:'transparent'},border:{color:'#006400',alpha:0,wmode:'transparent'},over:{fill:{color:'#006400',alpha:0,wmode:'transparent'},border:{color:'#000',alpha:0,wmode:'transparent'},width:16,height:16}}}}};var myAxes={dateRange:{keys:['date'],position:'bottom',type:'category',title:'Date Range',styles:{majorTicks:{display:'none'},label:{rotation:-45,margin:{top:5}},title:{fontSize:'90%'}}}};var mychart=new Y.Chart({dataProvider:myDataValues,interactionType:'planar',render:'#mychart',categoryKey:'Date',styles:styleDef,categoryType:'time',horizontalGridlines:{styles:{line:{color:'#fff'}}},verticalGridlines:{styles:{line:{color:'#fff'}}}})});\n\n"];
var simpleHead = [scriptHead];
var simpleTail = [scriptTail];
var oldData = JSON.parse(result, revive);
HTML code for form (in body):
form style="width:200px; color:#333; padding-right:5px; padding-bottom:2px; padding-left:55px; margin-top:0px; clear:none;" name="properties" id="properties">
select style="width:160px; color:#333; clear:none; display:block;" name="fabrics" id="fabrics" onChange="selectFabric()">
option value="nothing">Select Fabric END option
option value="KOD23-4074-LV">KOD23-4074-LV END option
option value="SGOD2-2858-LV">SGOD2-2858-LV END option
option value="W-897-LV">W-897-LV END option
option value="FF-4084-LV">FF-4084-LV END option
END select
END form
JavaScript code for chart (write script in body to render YUI chart plug-in):
document.write('\x3Cscript type="text/javascript" id="source">');
document.write(simpleHead[0] + '\n{Date: "' + oldData.results.bindings[0].date + '", Liability: ' + oldData.results.bindings[0].liability + ", Stock: " + oldData.results.bindings[0].stock + ", " + oldData.results.bindings[0].event + ": " + oldData.results.bindings[0].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[1].date + '", Liability: ' + oldData.results.bindings[1].liability + ", Stock: " + oldData.results.bindings[1].stock + ", " + oldData.results.bindings[1].event + ": " + oldData.results.bindings[1].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[2].date + '", Liability: ' + oldData.results.bindings[2].liability + ", Stock: " + oldData.results.bindings[2].stock + ", " + oldData.results.bindings[2].event + ": " + oldData.results.bindings[2].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[3].date + '", Liability: ' + oldData.results.bindings[3].liability + ", Stock: " + oldData.results.bindings[3].stock + ", " + oldData.results.bindings[3].event + ": " + oldData.results.bindings[3].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[4].date + '", Liability: ' + oldData.results.bindings[4].liability + ", Stock: " + oldData.results.bindings[4].stock + ", " + oldData.results.bindings[4].event + ": " + oldData.results.bindings[4].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[5].date + '", Liability: ' + oldData.results.bindings[5].liability + ", Stock: " + oldData.results.bindings[5].stock + ", " + oldData.results.bindings[5].event + ": " + oldData.results.bindings[5].current + "}," + "\n\n");
document.write('\n{Date: "' + oldData.results.bindings[6].date + '", Liability: ' + oldData.results.bindings[6].liability + ", Stock: " + oldData.results.bindings[6].stock + ", " + oldData.results.bindings[6].event + ": " + oldData.results.bindings[6].current + "}" + simpleTail[0] + "\n\n");
document.write('\x3C/script>');

Categories