Javascript and HTML button to INSERT MySQL query - javascript

I can't use AJAX/PHP solution to upload some data to MySQL database by clicking html button so I created .js function.
upload.js:
function uploadLikes(post) {
// credentials
var pass = require("/home/user/auth.json");
var passString = JSON.stringify(pass);
var passJson = JSON.parse(passString);
var mysql = require("mysql");
var connection = mysql.createConnection({
host : passJson.bi_anr.host,
user : passJson.bi_anr.user,
password : passJson.bi_anr.password,
});
// source: https://stackoverflow.com/questions/5818312/mysql-with-node-js
connection.connect(function(err) {
// connected! (unless `err` is set)
});
var query = connection.query("INSERT INTO db.likes (max_hash, ts, likes) VALUES (?, unix_timestamp(now() ), 1 ) ;", post, function(err, result) {
// Neat!
});
//console.log(query.sql);
}
and according to THIS I created button with javascript execution:
HTML file:
<html>
<head>
<title>Like Button</title>
</head>
<body>
<script src="upload.js"></script>
<input id="clickMe" type="button" value="clickme" />
<script>
//- Using a function pointer:
document.getElementById("clickMe").onclick = uploadLikes('TEST');
</script>
</body>
</html>
but it does not work. JavaScript function is OK, because it works by executing it in terminal using node. Could you help me?

Related

How to pass python json.dump() to print in <p> </p> in html?

I this simple scenario I am trying to create and dump a json string via python then parse the json dump and print it via html.
python:
import json
pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True}
dictionaryToJson = json.dumps(pythonDictionary)
html & js
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p id="messages"></p>
<p>My first paragraph.</p>
<script>
document.getElementById("messages").innerHTML = dictionaryToJson;
</script>
</body>
</html>
You can use python-shell like the following
var PythonShell = require('python-shell');
var pyshell = new PythonShell("code.py");
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
document.getElementById("messages").innerHTML = message;
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
I am assuming code.py contains the python codes
import json
pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True}
dictionaryToJson = json.dumps(pythonDictionary)
print(dictionaryToJson )

Writing javascript in PHP

I am new to PHP, I just need to write a javascript code inside php file like we doing in jsp.
Below is the sample code where am trying to do that, Please help me out to embed my javascript code in php
getencryp.php
<html>
<body>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript" src="js/jsencrypt.js"></script>
<script type="text/javascript">
var b=getAccountbyEncrptInfo('xxx','yyyy')
function getAccountbyEncrptInfo(user,pass)
{
var omegaKey = 'abc';
var crypt = new JSEncrypt();
crypt.setPublicKey(omegaKey);
var creds = {
username: user,
password: pass
};
creds.username = crypt.encrypt(creds.username);
creds.password = crypt.encrypt(creds.password);
return JSON.stringify(creds);
}
</script>
<?php
echo Your encrypted username and password is $b;
?>
</body>
</html>
In the above code am just passing two values in java script getAccountbyEncrptInfo('xxx','yyyy') and just trying to print inside php body.
b is a variable in javascript and it's not a variable in PHP. So that you can't echo it in the PHP tag.
I think you should implement the function getAccountbyEncrptInfo in PHP code or binding the variable from javascript into the html tag instead of using echo in PHP. It should be something like:
<html>
<body>
<script type="text/javascript" src="js/require.js"></script>
<script type="text/javascript" src="js/jsencrypt.js"></script>
<script type="text/javascript">
var b=getAccountbyEncrptInfo('xxx','yyyy');
document.getElementById('encrypted').html(b);
function getAccountbyEncrptInfo(user,pass)
{
var omegaKey = 'abc';
var crypt = new JSEncrypt();
crypt.setPublicKey(omegaKey);
var creds = {
username: user,
password: pass
};
creds.username = crypt.encrypt(creds.username);
creds.password = crypt.encrypt(creds.password);
return JSON.stringify(creds);
}
</script>
<div id="encrypted"></div>
</body>
</html>
Why do you need to use PHP?
<script>
var b = getAccountbyEncrptInfo('xxx','yyyy');
document.getElementById('ex').append(" Your encrypted username and password is " + b)
</script>
However if you wanted to append it inside the <?php ?> tags to further process your data, you might want to consider using an AJAX request.
just add this line after var b declaration
$('#answer').html(b);
and replace
echo Your encrypted username and password is $b;
this line with this line
Your encrypted username and password is div id="answer"></div
just make a blank div and set it`s id answer so js is set the value on it

Failing to get simple SoundCloud javascript api method to work

I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks
Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>

Using JavaScript to get information from BigQuery

I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --#citizenslave
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!

could not open db , $ is not defined, Failed to load jquery

The error is that the db could not be opened and $ not defined, failed to load resources(j query).The code aims at receiving the input field values(date,cal) and storing them into the database using indexedDB
<!DOCTYPE html>
<html manifest="manifest.webapp" lang="en">
<head>
<meta charset="utf-8">
<title>Diab</title>
<link rel="stylesheet" href="diab.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0/jquery.min.js"></script>
<script type="text/javascript" src="diab1.js"></script>
</head>
<body>
<input type="date" id="date">Date</input>
<input type="number" id="cal">Cal</input>
<button id="add" >Add</button>
</body>
</html>
(function()
{ var db;
var openDb=function()
{
var request=indexedDB.open("diabetore");
request.onsuccess = function()
{
console.log("DB created succcessfully");
db = request.result;
console.log("openDB done!!");
};
request.onerror=function(){
alert("could not open db");
};
request.onupgradeneeded = function()
{
console.log("openDB.onupgradeneeded function");
var store = db.createObjectStore("diab", {keyPath: "date"});
var dateIndex = store.createIndex("date", "date",{unique: true});
// Populate with initial data.
store.put({date: "june 1 2013",cal:70});
store.put({date: "june 2 2013",cal:71});
store.put({date: "june 3 2013",cal:72});
store.put({date: "june 8 2013",cal:73});
};
};
function getObjectStore(store_name,mode)
{
var tx=db.transaction(store_name,mode);
return tx.objectStore(store_name);
}
function addItems(date,cal)
{
console.log("addition to db started");
var obj={date:date,cal:cal};
var store=getObjectStore("diab",'readwrite');
var req;
try
{
req=store.add(obj);
}catch(e)
{
if(e.name=='DataCloneError')
alert("This engine doesn't know how to clone");
throw(e);
}
req.onsuccess=function(evt)
{
console.log("****Insertion in DB successful!!****");
};
req.onerror=function(evt)
{
console.log("Could not insert into DB");
};
}
function addEventListners()
{
console.log("addEventListeners called...");
$('#add').click(function(evt){
console.log("add...");
var date=$('#date').val();
var cal=$('#cal').val();
if(!date || !cal)
{
alert("required field missing..");
return;
}
addItems(date,cal);
});
}
openDb();
addEventListners();
})();
Regarding the problem of not being able to see the db created, when you open the database you should pass another parameter with the version of the database, like:
var request=indexedDB.open("diabetore",1);
To see the DB structure on the Resources tab of Chrome Developer Tools, sometimes you must refresh the page.
You will also have a problem with your addEventListners() function since your anonymous function is run before the browser reads the HTML content so the browser doesn't not know about the '#add' element, so the click event handler for that element is not created.
You should put your code inside "$(function() {" or "$(document).ready(function() {":
$(function() {
(function() {
var db;
var openDb=function() {
You should test the script URL in your browser. Then you'd realize that the script doesn't exist.
You need to change 2.0 to 2.0.0 for example.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

Categories

Resources