Commit 0a6225dd authored by Clara Stoddart's avatar Clara Stoddart

Successfully connected to database

parent e5097598
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'database.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'There was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
hello this is ajax
This diff is collapsed.
......@@ -2,10 +2,7 @@
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited_true';
var MOUSE_VISITED_CLASSNAME_FALSE = 'crx_mouse_visited_false';
var srcName;
// var requestResult;
var dietNum = 0;
function dietNumInit() {
......@@ -16,172 +13,49 @@ function dietNumInit() {
dietNum = a + (b << 1) + (c << 2) + (d << 3);
}
// function initialise() {
// var db = new SQL.Database(public.db);
//
// }
// function query(product) {
// const sqlite3 = require('sqlite3').verbose();
// let db = new sqlite3.Database('./public.db', sqlite3.OPEN_READONLY, (err) => {
// if (err) {
// console.error('Error connecting to database');
// }
// console.log('Connected to the in-memory SQlite database.');
// });
// let sql = `SELECT Containsdairy cd,
// Containsmeat cm,
// Containscorn cc,
// Containsgluten cg
// FROM productsIngredients
// WHERE Product = ?`;
// db.get(sql, product, (err, row) => {
// if (err) {
// return console.error('Error querying database');
// }
// if (!row) {
// return console.error(`No product found with the name ${product}`);
// }
// return !((cd && (1 && dietNum)) || (cm && (2 && dietNum)) || (cc && (4 && dietNum)) || (cg && (8 && dietNum)))
// });
// db.close();
// }
// function callBack(canEat) {
// if (canEat == undefined) {
// requestResult = true;
// } else if (canEat == "0") {
// requestResult = true;
// } else if (canEat == "1") {
// requestResult = true;
// } else if (canEat == "Could not connect") {
// result = true;
// } else if (canEat == 1) {
// requestResult = true;
// } else if (canEat == '1') {
// requestResult = true;
// }
// }
// function checkAllergen(product) {
// request(product);
// return requestResult;
// }
// function checkAllergen(product) {
// var xhr = new XMLHttpRequest();
// var result;
// xhr.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// var canEat = this.responseText;
// if (canEat == undefined) {
// result = false;
// } else if (canEat == "0") {
// result = false;
// } else if (canEat == "1") {
// result = true;
// } else if (canEat == "Could not connect") {
// result = false;
// }
// }
// };
// xhr.open("GET", "script.php?q="+product, true);
// xhr.send();
// return result;
// }
// function checkAllergen(product) {
// var xhr = new XMLHttpRequest();
// var result;
// xhr.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// var canEat = this.responseText;
// if (canEat == undefined) {
// result = false;
// } else if (canEat == "0") {
// result = false;
// } else if (canEat == "1") {
// result = true;
// } else if (canEat == "Could not connect") {
// result = false;
// }
// }
// };
// xhr.open("GET", "script.php?q="+product, true);
// xhr.send();
// return result;
// }
//
function checkAllergen(product) {
var db = new SQL.Database();
var sqlstr = "CREATE TABLE productsingredients (product character varying(255), containsgluten boolean, containsdairy boolean, containscorn boolean, containsmeat boolean);";
sqlstr += "INSERT INTO productsingredients VALUES ('6 Chocolate Fairy Cakes', true, true, true, false);"
db.run(sqlstr);
let sql = `SELECT containsdairy cd,
containsmeat cm,
containscorn cc,
containsgluten cg
FROM productsIngredients
WHERE product=:prod`;
// WHERE Product = ` + product
var stmt = db.prepare(sql);
var result = stmt.getAsObject({':prod' : product});
console.log(result);
return !((cd && (1 && dietNum)) || (cm && (2 && dietNum)) || (cc && (4 && dietNum)) || (cg && (8 && dietNum)));
var promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
var result;
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var canEat = this.responseText;
resolve(canEat);
}
};
xhr.onerror = () => reject(xhr.status);
xhr.open("GET", "http://localhost/script.php?product="+product+"&dietNum="+2, true);
xhr.send();
});
return promise;
}
// Previous dom, that we want to track, so we can remove the previous styling.
//var prevDOM = null;
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
let srcElement = e.srcElement;
// Lets check if our underlying element contains any allergens.
if (srcElement.nodeName == 'IMG') {
//if (srcElement.nodeName == 'DIV' && srcElement.className == "content___1O9rr") {
//prevDOM != srcElement &&
srcName = srcElement.alt;
// For NPE checking, we check safely. We need to remove the class name
// Since we will be styling the new one after.
// if (prevDOM != null) {
// prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
// }
// Add a visited class name to the element. So we can style it.
// if (srcName == "Waitrose coffee & walnut cake") {
// srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
// }
// currName = srcElement.srcName;
var canEat = checkAllergen('6 Chocolate Fairy Cakes');
if (canEat) {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME); //changes outline of pic
}
if (!canEat) {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME_FALSE);
}
//TODO: modify behaviour according to different allergens
// The current element is now the previous. So we can remove the class
// during the next ieration.
//prevDOM = srcElement;
promise = checkAllergen(srcName).then(
function(responseText) {
console.log("Success");
if (responseText == "1" || responseText == undefined) {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
} else if (responseText == "0") {
srcElement.classList.add(MOUSE_VISITED_CLASSNAME_FALSE);
}
},
function(failureStatus) {
console.log(failureStatus);
if (failureStatus == 0) {
console.log("Not in database");
}
});
console.info(srcElement.currentSrc);
console.dir(srcElement);
}
}, false);
if(document){
if (document){
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("Submit").addEventListener("click", dietNumInit);
});
......
<?php
$product = $_GET['q'];
$product = $_GET['product'];
$dietNum = $_GET['dietNum'];
$con = mysqli_connect('localhost','root','','public');
if (!$con) {
echo "Could not connect";
//die('Could not connect: ' . mysqli_error($con));
}
// $sql = "SELECT containsgluten FROM productsingredients WHERE product = $product";
$sql = "SELECT containsgluten FROM productsingredients WHERE product = Waitrose Delicious & Zingy Lemon Loaf Cake";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
$edible = $row['containsgluten'];
// $row = mysqli_fetch_array($result, 'MYSQLI_ASSOC');
// $edible = $row['containsgluten'];
if ($edible == 1) {
echo "1";
$stmt = $con->prepare("SELECT containsgluten, containsdairy, containscorn, containsmeat FROM productsingredients WHERE product = ?");
if ($stmt == false) {
echo "Malformed statement";
} else {
echo "0";
$stmt->bind_param('s', $product);
}
$stmt->execute();
$stmt->bind_result($containsgluten, $containsdairy, $containscorn, $containsmeat);
$result = $stmt->fetch();
if ($result == false) {
echo "8";
} else {
if (!(($containsdairy & (1 & $dietNum)) | ($containsmeat & (2 & $dietNum)) | ($containscorn & (4 & $dietNum)) | ($containsgluten & (8 & $dietNum)))) {
echo "1";
} else {
echo "0";
}
}
mysqli_close($con);
?>
......@@ -6,12 +6,9 @@
"permissions": [
"activeTab",
"declarativeContent"
],
"permissions": [
"activeTab",
"declarativeContent"
"declarativeContent",
"https://www.waitrose.com/",
"http://localhost/"
],
"browser_action": {
......
//https://www.w3schools.com/nodejs/nodejs_mysql_select.asp
// two options for accessing database:
// 1. make it a function and connect and reconnect to the client each time we hover over an icon
// problem: connecting to the client within content.js?
// --> figure out how to call function from diff javascript file? and put the function here in index.js
// problem: cost of calling database that many times?
// --> probably not a big deal, can ignore (?)
// 2. store the entire database in the cache or something and load it once at startup
// problem: slows down the browser probably lmao
// --> cant really fix this? unless its negligible but i dont think so (?)
\ No newline at end of file
......@@ -13,10 +13,10 @@
.crx_mouse_visited_true {
background-clip: #bcd5eb!important;
outline: 1px dashed #47bb47!important;
outline: 2px solid #47bb47!important;
}
.crx_mouse_visited_false {
background-clip: #bcd5eb!important;
outline: 1px dashed #fa1100!important;
outline: 2px solid #fa1100!important;
}
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="masterDetails">
<states>
<state key="ProjectJDKs.UI">
<settings>
<last-edited>11</last-edited>
<splitter-proportions>
<option name="proportions">
<list>
<option value="0.2" />
</list>
</option>
</splitter-proportions>
</settings>
</state>
</states>
</component>
</project>
\ No newline at end of file
# Default ignored files
/workspace.xml
\ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<DBN-PSQL>
<case-options enabled="true">
<option name="KEYWORD_CASE" value="lower" />
<option name="FUNCTION_CASE" value="lower" />
<option name="PARAMETER_CASE" value="lower" />
<option name="DATATYPE_CASE" value="lower" />
<option name="OBJECT_CASE" value="preserve" />
</case-options>
<formatting-settings enabled="false" />
</DBN-PSQL>
<DBN-SQL>
<case-options enabled="true">
<option name="KEYWORD_CASE" value="lower" />
<option name="FUNCTION_CASE" value="lower" />
<option name="PARAMETER_CASE" value="lower" />
<option name="DATATYPE_CASE" value="lower" />
<option name="OBJECT_CASE" value="preserve" />
</case-options>
<formatting-settings enabled="false">
<option name="STATEMENT_SPACING" value="one_line" />
<option name="CLAUSE_CHOP_DOWN" value="chop_down_if_statement_long" />
<option name="ITERATION_ELEMENTS_WRAPPING" value="chop_down_if_not_single" />
</formatting-settings>
</DBN-SQL>
</code_scheme>
</component>
\ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GoogleJavaFormatSettings">
<option name="enabled" value="false" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_11" default="true" project-jdk-name="11" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/untitled.iml" filepath="$PROJECT_DIR$/untitled.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment