I have some trouble with my js callback, I can't understand why my callback of my function don't want execute all the code, just to give you an idea :
class LogsPortail {
static SetLogs(pool, req, res, callback) {
console.log('start log ');
var bCallBack = false;
var now = new Date();
var endpoint = req.originalUrl
endpoint = endpoint.split("?")[0]
endpoint = endpoint.replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
var queryParam = "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ";
console.log('query 1 log ');
pool.query(query, function(err, results) {
if (err) {
console.log("Error : " + query);
bCallBack = true;
callback();
} else {
console.log('query log 2');
//On a bien inséré le logs portail, maintenant on ajout tous les paramètres
for (var key in req.query) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.query[key] + "')"
}
for (var key in req.body) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.body[key] + "')"
}
pool.query(queryParam, function(err, resultsParam) {
if (err) {
console.log("Error : " + queryParam);
console.log(err);
bCallBack = true;
callback();
} else {
bCallBack = true;
callback();
}
});
}
});
while (bCallBack === false) {}
console.log('call back end ');
//callback();
}
}
To explain you, my first query will be executed perfectly, and after that, the callback will not go through the condition but will go at the end where (for the test) I put an infinity while where my code will never exit.
This is what my log shows - we never see the logs "query log 2"
Thanks for your help
I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc
I've tried all possible formats for the select query:
var queryCust = "SELECT * FROM customers WHERE CustBarcode = '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE CustBarcode like '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE cast(CustBarcode as text) = '" + CustomerBarcode "';";
or with and without ' ' but nothing works, the query didn't return any value!
I've even tried
db.executeSql('SELECT * FROM customers WHERE CustBarcode = ?', [ CustBarcode ], function(rs) {...
but didn't worked, even when tried to convert with javascript CustBarcode to string or integer.
below is the function:
alert(queryCust);
db.executeSql(queryCust, [], function(rs) {
alert(rs.rows.item(0).CustBarcode);
var DescCust = "";
if (rs.rows.item(0).Status == 'NEW'){
DescCust = rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
} else {
DescCust = rs.rows.item(0).CustCode + ' ' + rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
}
document.getElementById("custDesc").innerHTML = DescCust;
}, function(error) {
alert('SELECT SQL statement ERROR while building DescCust: ' + error.message);
});
** i'm developing a phonegap application but it cannot connect the database i attached the following program? my code is below:**
function onDeviceReady() {
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
db = window.openDatabase("RegistrationDB", "1.0", "Registration", 200000);
if (dbCreated)
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS Registration');
var sql = "CREATE TABLE IF NOT EXISTS Registration ( "
+ "mobno INTEGER(50), " + "custname VARCHAR(50))";
tx.executeSql(sql);
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
tx.executeSql("INSERT INTO Registration (mobno,custname) VALUES ('"+ mobno +"','"+ cust +"')");
}
function transaction_error(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
// where you want to move
alert("Successfully inserted");
window.location="file:///android_asset/www/login.html";
}
If you would like to use the Cordova SqlLite plugin you have to install it:
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
next you can create the db in device ready:
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}
I want to make an app with Phonegap, but I have problems with the Web SQL coding.
The app is very simple: button1 to pick current time and set on value1, then button1 pick current time again and set to value2; a field to identificate the activity and after all fields are filled, button1 again to open a dialog box to OBS, and then open a new page with all activities:
// JavaScript Documentvar db;
var dbCreated = false;
/*var scroll = new iScroll('wrapper', {
vScrollbar : false,
hScrollbar : false,
hScroll : false
}); */
document.addEventListener("deviceready", onDeviceReady, false);
var ativ = document.getElementById("ativ").value;
var hi = document.getElementById("hi").value;
var hf = document.getElementById("hf").value;
var obs = document.getElementById("obs").value;
function onDeviceReady() {
db = openDatabase("RegistrationDB", "1.0", "Registration", 1024 * 1024);
if (dbCreated) {
} else {
db.transaction(populateDB, transaction_error, populateDB_success);
}
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS RegistrationDB');
var sql = "CREATE TABLE IF NOT EXISTS RegistrationDB ( " + " atividade, " + " horaInicial, " + " horaFinal, " + " observacao)";
tx.executeSql(sql);
tx.executeSql("INSERT INTO RegistrationDB (atividade, horaInicial, horaFinal, observacao) VALUES ('" + ativ + "','" + hi + "' , " + hf + ", '" + obs + "')");
}
function transaction_error(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
// where you want to move
alert("Successfully inserted");
window.location="tela2.html";
}// JavaScript Document