Commit b68ed7a5 authored by Zhai Zirun's avatar Zhai Zirun

fixed stupid merging errors

parent d89c0080
// 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.
// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited_true';
var MOUSE_VISITED_CLASSNAME_FALSE = 'crx_mouse_visited_false';
var srcName;
var db;
// var requestResult;
var dietNum = 0;
function dietNumInit() {
var a = document.getElementById("Dairy").checked;
var b = document.getElementById("Meat").checked;
var c = document.getElementById("Corn").checked;
var d = document.getElementById("Gluten").checked;
dietNum = a + (b << 1) + (c << 2) + (d << 3);
}
function initialize() {
var Uints = new Uint8Array("./public.db");
db = new SqlJs.Database(Uints);
}
// 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 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;
initialize();
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;
console.info(srcElement.currentSrc);
console.dir(srcElement);
}
}, false);
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){
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("Submit").addEventListener("click", dietNumInit);
document.getElementById("Submit").addEventListener("click", initialize);
});
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("Submit").addEventListener("click", dietNumInit);
});
}
\ No newline at end of file
<?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);
?>
{
"name": "Clickerance",
"description": "Makes shopping with food requirements easier",
"version": "1.0",
"manifest_version" : 2,
"permissions": [
"activeTab",
"declarativeContent"
],
"permissions": [
"activeTab",
"declarativeContent"
],
"browser_action": {
"default_icon": "images/example-icon.png",
"default_title": "Clickerance",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"css": ["style.css"],
"js": ["content.js"],
"matches": ["https://www.waitrose.com/ecom/shop/browse/groceries/*"]
}]
"name": "Clickerance",
"description": "Makes shopping with food requirements easier",
"version": "1.0",
"manifest_version" : 2,
"permissions": [
"activeTab",
"declarativeContent",
"https://www.waitrose.com/",
"http://localhost/"
],
"browser_action": {
"default_icon": "images/example-icon.png",
"default_title": "Clickerance",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [{
"css": ["style.css"],
"js": ["content.js"],
"matches": ["https://www.waitrose.com/ecom/shop/browse/groceries/*"]
}]
......
......@@ -896,9 +896,7 @@
"resolved": "https://registry.npmjs.org/sql-js/-/sql-js-0.1.0.tgz",
"integrity": "sha1-OSkM2Rv7yd/8G+Gy+g6WGF7ZQGc="
},
"sql.js": {
"version": "file:sql.js"
},
"sqlite3": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-5.0.0.tgz",
......
......@@ -16,7 +16,6 @@
"dependencies": {
"pg": "^8.3.0",
"sql-js": "^0.1.0",
"sql.js": "file:sql.js",
"sqlite3": "^5.0.0",
"uniq": "^1.0.1",
"xmlhttprequest": "^1.8.0"
......
//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;
}
const Ingredient = {
GLUTEN: 1,
DAIRY: 2,
CORN: 3,
MEAT: 4
};
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./public.db', sqlite3.OPEN_READONLY, (err) => {
if (err) {
console.error(err.message);
}
console.log('Connected to the in-memory SQlite database.');
});
let ingredient = Ingredient.GLUTEN;
let product = 'Waitrose Millionaire Bites'
let sql = `SELECT Containsgluten cg,
Containsdairy cd,
Containscorn cc,
Containsmeat cm
FROM productsIngredients
WHERE Product = ?`;
db.get(sql, product, (err, row) => {
if (err) {
return console.error(err.message);
}
switch(ingredient) {
case Ingredient.GLUTEN:
return row
? console.log(row.cg)
: console.log(`No product found with the name ${product}`);
case Ingredient.DAIRY:
return row
? console.log(row.cd)
: console.log(`No product found with the name ${product}`);
case Ingredient.CORN:
return row
? console.log(row.cc)
: console.log(`No product found with the name ${product}`);
case Ingredient.MEAT:
return row
? console.log(row.cm)
: console.log(`No product found with the name ${product}`);
default:
break;
}
});
db.close((err) => {
if (err) {
console.error(err.message);
}
console.log('Database connection closed.');
});
\ No newline at end of file
<?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
-- PostgreSQL database dump
--
-- Dumped from database version 12.3
-- Dumped by pg_dump version 12.3
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Data for Name: productsingredients; Type: TABLE DATA; Schema: public; Owner: postgres
--
INSERT INTO public.productsingredients (product, containsgluten, containsdairy, containscorn, containsmeat) VALUES ('6 Chocolate Fairy Cakes', true, true, true, false);
INSERT INTO public.productsingredients (product, containsgluten, containsdairy, containscorn, containsmeat) VALUES ('Waitrose salted caramel cake', true, true, true, false);
INSERT INTO public.productsingredients (product, containsgluten, containsdairy, containscorn, containsmeat) VALUES ('essential Waitrose plain cup cakes', true, false, true, false);
INSERT INTO public.productsingredients (product, containsgluten, containsdairy, containscorn, containsmeat) VALUES ('Bonne Maman 7 Financiers Amandes', true, true, false, false);