I'm a newbie around here and of course, I am newbie also to the nodejs technology.
I'm writing to you because I have a big problem for me, maybe a little problem for you, with the following:
I have this part of the code and I want when a user clicks on a button then the user should insert 3 values for him: UserId, GameId, Bookid. Then I want with the help of node js to print the results to my console. But i see from F12 that it says there is a problem with this line
loadnodejs.html:9 Uncaught ReferenceError: require is not defined --> var mysql = require('mysql');.
I've done the procedure from w3schools but nothing is showing. Can you help me to print the results on my console?
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function load3() {
do{
var selection = window.prompt("Give the User Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection)) {
flag1=false;
}
}while(flag1!=false);
var flag2 = true;
do{
var selection2 = window.prompt("Give the Book Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection2)) {
flag2=false;
}
}while(flag2!=false);
var flag3= true;
do{
var selection3 = window.prompt("Give the Game Id:", "Type a number!");
if ( /^[0-9]+$/.test(selection3)) {
flag3=false;
}
}while(flag3!=false);
var mysql = require('mysql');
var con = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "",
database: "mysql3"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM components", function (err, result) {
if (err) throw err;
console.log(result);
});
});
}
</script>
</head>
<body>
<input type="button" value="Load" id="load" onclick="load3()" class="button12" />
</body>
</html>
Node.js is JavaScript which runs on backend. You have added Node.js code to an HTML file, which runs in browser. Browser doesn't support Node.js and hence the error.
Make an API call to server, and move Node.js code to server. I hope it makes sense to you.
Node.JS is a server-side technology, not a browser technology. Thus, Node-specific calls, like require(), do not work in the browser.
See [browserify]:http://browserify.org/ or webpack if you wish to serve browser-specific modules from Node.
Related
I'm new in web developing.
I want to query an SQLite database from HTML script balise.
for more details, I share my code.
function test() {
var fullname;
var fname = "bishoy";
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./Basket.db');
let sql = 'SELECT * FROM [Source: players]';
db.each(sql, [fname], (err, row) => {
if (err) {
throw err;
}
fullname = ('${row.Name}');
alert(fullname);;
});
db.close();
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button type="button" onclick="test()" style="font-family:cambria;
">Execute</button>
</body>
</html>
the problem that I encounter when I execute it on my Chrome browser: storage.html:8 Uncaught ReferenceError: require is not defined
at test (storage.html:8)
at HTMLButtonElement.onclick (storage.html:22)
, please someone can help me to fix the problem.
I have been practicing with a simple html form to mysql using nodejs, but it doesnt seem to work, the html is called index.html and my nodejs file is called test.js, here is my code:
My html
<!DOCTYPE html>
<html>
<head>
<title>email test form</title>
</head>
<body>
<form method="post" action="/data">
<label for="email">Voer je email in </label> <input type="email"
name="email"></input>
<input type="submit" value="submit">
</form>
<script src="test.js"></script>
</body>
</html>\
My javascript for node js:
var express = require('express');
var app = express();
var mysql = require('mysql');
var bodyParser = require ('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Bionicle123!",
database: "account"
});
con.connect(function(err){
if (err) throw err;
console.log("Je bent verbonden aan de database!");
});
app.post("/data", function(req, res) {
var userEmail = req.body.email;
console.log(userEmail);
var sql = "INSERT INTO persoon (email) VALUES (?)";
con.query(sql, userEmail, function (err, data) {
if (err) {
console.log("Failed ah mattie!");
} else {
console.log("Gelukt ah mattie!");
}
});
});
Uncaught ReferenceError: require is not defined at test.js:1
You've tagged this question node.js.
You need to run your JavaScript using Node.js.
Download it from https://nodejs.org/en/ , then install it, then run node test.js.
Not allowed to load local resource: file:///C:/newuser
You need to load your HTML document from the webserver that you write using Node.js. Otherwise the action URL won't point to the right place.
… but first you need to finish writing the web server. Look at the Hello World example for Express.js (which you are also using).
You need to call listen. That will give you a URL you are point the browser to.
I'm totally new to node.js and I want to implement push notification system on a MySql database. I have a notification table in my database. In this table I have store recipient_id that specify the recipient of the notification. Now I want when a new notification with recipient_id is equal to current logged in user's id notify that user. Something like Stackoverflow If you are in the for example java tagged questions, every time a new question with java tag create, a notification appear on top of the page : 1 question with new activity.
Sorry for my poor English. Please help me to implement this system, because I'm new to it.
I have made a simple app like your requirement.
You can get help from following lines of code.You need to understand the basics of code. after that you will easily achieve your target. most of things from your requirement covered in this demo app.
Its not a exact but you will meet your target through this.
In this example a status post by any user will emit to all other users also at same time. we can manipulate it to achieve "1 new status".
make a table in database where your entries to be saved
CREATE TABLE status
(
`status_id` INT NOT NULL AUTO_INCREMENT,
`s_text` TEXT,
`t_status` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY ( `status_id` )
);
//server.js
var app = require("express")();
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require("socket.io")(http);
/* Creating POOL MySQL connection.*/
var pool = mysql.createPool({
connectionLimit: 100,
host: 'localhost',
user: 'root',
password: '',
database: 'fbstatus',
debug: false
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
socket.on('status added', function(status) {
add_status(status, function(res) {
if (res) {
io.emit('new status', status);
} else {
io.emit('error');
}
});
});
});
var add_status = function(status, callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("INSERT INTO `status` (`s_text`) VALUES ('" + status + "')", function(err, rows) {
connection.release();
if (!err) {
callback(true);
}
});
connection.on('error', function(err) {
callback(false);
return;
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
//index.html
<html>
<head>
<title>Socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var socket = io();
$("#add_status").click(function(){
socket.emit('status added',$("#comment").val());
});
socket.on('new status',function(msg){
var count = $('#count_status').text();
var valCount = parseInt(count);
if(valCount>=1) {
valCount = valCount+1;
} else {
valCount = 1;
}
var showMsg = '<div id="count_status"> '+valCount+' </div> new status';
$("#show_comments").html(showMsg);
});
});
</script>
</head>
<body>
<div id="comment_box" style = "padding:5%;">
<textarea id="comment" rows="5" cols="70"></textarea><br /><br />
<input type="button" id="add_status" value="Add">
</div>
<div id= "show_comments" class = "jumbotron"></div>
</body>
</html>
Run the app with following command
node Server.js
Now run http://localhost:3000/ in browser and to see the result open a new window in which you post a status and see your new status notification in both the window.
Thanks
Edited: This a great startup tutorial. a few thing needs modification.
connection.release() code ends up unreadable and not working. you should comets or remove it.
2.The actual output in my case:
You can do it 2 ways:
Query the server every n seconds for any new messages. Pass a timestamp of the last time you checked as a parameter and if any notification since the last check, return as json and display them in the client. This is called a pull strategy.
Or you can use websockets which maintains a permanent connection between your client and server, and then you can send notifications to the client from your server code in real-time. See socket.io tutorials. This is called a push strategy.
Using the first Geoip I was using a simple Javascript code (as seen below), but I've been trying all day to figure out what I need to do to have the script recognise the country code for Maxmind Javascript Geoip2.
The Original GEOip code
<script type="text/javascript">
var user_country = geoip_country_code();
if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>
What I have in the new header
<script type="text/javascript" src="//j.maxmind.com/js/apis/geoip2/v2.0/geoip2.js"></script>
The latest code that I have attempted to use.
<script type="text/javascript">
var user_country = geoip2.cityISPOrg.country.iso_code();
if(user_country == "US")
document.write(hockeyAds[4]);
else
document.write(hockeyAds[5]);
</script>
Below on the same page I have tried this script that someone made and I was able to get it to type out the correct country code. So I am convinced that it is a problem with the above javascript code.
<script>
geoip2.cityISPOrg(function (response) {
$("#usercountry").html(response.country.iso_code);
});
</script>
<p>
<span id="usercountry"></span>
</p>
Not really all the great with understanding Javascript.
Thanks
You need to pass success and error callbacks to the geoip2 methods. Try this:
geoip2.country(
function (response) {
if (response.country.iso_code === "US") {
document.write(hockeyAds[4]);
} else {
document.write(hockeyAds[5]);
}
},
function (error) {
// handle error
}
);
Also, this tutorial might help you understand the API: http://dev.maxmind.com/geoip/geoip2/javascript/tutorial/
Im currently trying to get users timeline data from twitter through the oauth process and I cant get it to work.
I tried a few things here http://bytespider.github.com/jsOAuth/ and I keep running into the same problem.
Whoa there!
There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.
It cant be this hard to do this right?
Here is my code
<html>
<head>
<title></title>
</head>
<body>
<script src="jsOAuth-1.3.4.min.js"></script>
<script>
var config = {
consumerKey: "[removed]",
consumerSecret: "[removed]",
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizationUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
};
var oauth = new OAuth(config);
oauth.fetchRequestToken(openAuthoriseWindow, failureHandler);
function openAuthoriseWindow(url)
{
var wnd = window.open(url, 'authorise');
setTimeout(waitForPin, 100);
function waitForPin()
{
if (wnd.closed)
{
var pin = prompt("Please enter your PIN", "");
oauth.setVerifier(pin);
oauth.fetchAccessToken(getSomeData, failureHandler);
}
else
{
setTimeout(waitForPin, 100);
}
}
}
function getSomeData()
{
oauth.get("https://api.twitter.com/oauth/something/?format=jsonp", function (data) {
console.log(data.text);
}, failureHandler);
}
function failureHandler(data)
{
console.error(data);
}
</script>
</body>
</html>
I also get this error in console
OPTIONS https://api.twitter.com/oauth/request_token 403 (Forbidden)
EDIT: Does anyone know how to do this? Cant even find a good resource on twitter. Also can you achieve this without pin and just have users enter their login details?
Thanks in advance