I'm trying to send an Ajax request in HTML to fetch an object in a JSON file. here is my code in HTML:
<!DOCTYPE html>
<html>
<head>
<title>JSON Server Test</title>
<script type="text/javascript">
var findData = (id) => {
$('.submit-button').on('click', (e) => {
e.preventDefault();
console.log('submit button pressed');
var data = {};
data.title = "title";
data.message = "message";
$.ajax({
type: 'GET',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'localhost:3000/people?id=' + id,
success: (data) => {
console.log('success');
console.log(JSON.stringify(data));
}
});
});
};
</script>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var findData = (id) => {
$('.submit-button').on('click', (e) => {
e.preventDefault();
console.log('submit button pressed');
var data = {};
data.title = "title";
data.message = "message";
$.ajax({
type: 'GET',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'localhost:3000/people?id=' + id,
success: (data) => {
console.log('success');
console.log(JSON.stringify(data));
document.getElementById('final-data').innerHTML
= JSON.stringify(data);
}
});
});
};
</script>
<input id="input" type="number">
<button class="submit-button"
onclick="findData(getElementById('input').value)">Find
Person</button>
<p id="final-data"></p>
</body>
</html>
And here is my NodeJS code:
const express = require('express');
var app = express();
app.get('/', (req, res) => {
res.sendFile(__dirname + "/" + "index.html");
});
app.listen(4000, () => {
console.log('Listening on port 4000');
});
The actual server itself is running on a localhost on port 3000 using a json-server on a cmd.
json-server --watch db.json
The problem is when I actually press the "Submit" button in the frontend, nothing gives back a response. No console logging, no actual change in the paragraph element in the HTML, nothing.
EDIT: I did manage to do it, it works, but one more thing: I am getting an array with the data, but I want to break it so I get every property alone. How do I do that?
Related
I am running a local website with NodeJS on my Pi and I want to control a lamp via an 433MHz sender connected to the Pi. I have already written a bash script which works perfectly to control the lamp but I can't find a way to execute it through the HTML site on the node server.
So I am asking whether it is even possible because it doesn't really seem secure to me and how can I implement it in javascript as a function or only on the server side ?
there are many ways you could go about doing something like this but one way would be creating an api so your website can make api calls to the server to turn the light on and off
so here is a simple example
HTML
<html>
<head>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
<form>
<input type="button" Value="on" onclick="turnOn()">
<input type="button" value="off" onclick="turnOff()">
</form>
</body>
</html>
<script>
function turnOn(){
$.ajax({
url: 'http://localhost:3000/api/light/on',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(`Error ${error}`);
}
});
}
function turnOff(){
$.ajax({
url: 'http://localhost:3000/api/light/off',
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(`Error ${error}`);
}
});
}
</script>
SERVER
//server.js
const app = require('express')();
const server = require('http').createServer(app);
var cors = require('cors');
const shell = require('shelljs')
var port = 3000;
server.listen(port, () => console.log(`API server running on ${port}!`))
app.use(cors())
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
})
app.get('/api/light/:status', (req, res) => {
var status = req.param('status')
if(status == 'on'){
shell.exec('./turn-light-on')
res.json({success:"light turned on"})
}else{
shell.exec('./turn-light-off')
res.json({success:"light turned off"})
}
})
all you would have to do is change the file that shell.exec() calls for it to work
this app reqires
express
cors
shelljs
to be installed just npm install the names as listed above
I was making the TODO list web application.
This is the 'todo.html' code below :
<html>
<head>
<title>My TODO List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
<script>
$(document).ready(function() {
$("#submit").click(function() {
var bla = $('#item').val();
$("#todo").append("<li class='todoVal'>" + bla + "</li>");
});
// $(document).click(function(e) {
// if (e.target.className == 'todoVal') {
// var t = e.target.innerText
// $(e.target).remove();
// $("#completed").append("<li class='completedVal'>" + t + "</li>");
// }
// });
$(document).click(function(e) {
if (e.target.className == 'completedVal') {
$(e.target).remove();
}
});
jQuery.fn.single_double_click = function(single_click_callback, double_click_callback, timeout) {
return this.each(function() {
var clicks = 0,
self = this;
jQuery(this).click(function(event) {
clicks++;
if (clicks == 1) {
setTimeout(function() {
if (clicks == 1) {
single_click_callback.call(self, event);
} else {
double_click_callback.call(self, event);
}
clicks = 0;
}, timeout || 500);
}
});
});
}
$(document).single_double_click(function(e) {
if (e.target.className == 'todoVal') {
var t = e.target.innerText
$(e.target).remove();
$("#completed").append("<li class='completedVal'>" + t + "</li>");
}
}, function(e) {
if (e.target.className == 'todoVal') {
$(e.target).remove();
}
});
$("#clear").click(function() {
$("li").remove();
});
});
</script>
</head>
<body>
<div id="addItem" class="box">
Task:
<input id="item" type="text" name="add_item" />
<button id="submit" type="button">Add</button>
<button id="clear" type="button">Clear All</button>
</div>
<div id="todo" class="box">
<h4>TODO:</h4>
<ul></ul>
</div>
<div id="completed" class="box">
<h4>Completed:</h4>
<ul></ul>
</div>
</body>
</html>
And this is the 'app.js' file below :
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require("body-parser");
// middleware
app.use(cors());
app.use(bodyParser.json());
var tasks = [];
// This will serve the HTML page todo.html
app.get('/', function(req, res) {
res.sendFile('todo.html', {
root: __dirname
});
});
// GET all tasks
app.get('/tasks', function(req, res) {
res.set('Content-Type', 'application/json')
res.status(200).send(tasks);
});
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
/* HELP ME HERE */
// returns 201 on success
res.status(201);
});
// DELETE a task
app.delete('/task', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
// DELETE all tasks
app.delete('/tasks', function(req, res) {
/* HELP ME HERE */
// returns 204 on success
res.status(204);
});
//
// Listen for HTTP requests on port 3000
app.listen(3000, function() {
console.log("listening on port 3000");
});
I want to pass the text box value to the JSON filter by 'TODO' and 'COMPLETED'.
If I add a new TODO list, it goes to the JSON and if the value goes to COMPLETED, it also goes to the JSON
This is the sample JSON result I want:
{"TODO" : [ "Go to market", "Eat dinner with Daniel"], "COMPLETED" : [ "Wash dishes", "Go to gym and Workout" ]}
This is just an example so you guys can just change the format.
Feel free to give me feedback from everything it's always welcome. btw I just started studying how to code
Thank you for spending time on this even if you didn't help me and have a great day!
What you have to do is simply make an Ajax Call to Nodejs APIs. For example,to '/task' and pass the input field value as params in json format then simply fetch them on in Nodejs as req.params.yourjsonKeys.
var inputData = $("#items").val();
$.ajax({
url: "/tasks",
type: "POST",
data: {params: inputData},
dataType: "html",
success: function(data){
if(data.code === 200){ // the response key 'code' from Nodejs
alert('Success');
}
}
});
Next, once you have the params, all you have to do is write it into your file using file system like so:
Create a javascript object with the table array in it
var obj = {
table: []
};
Add some data to it like
obj.table.push({id: req.params.id , square: req.params.square});
Convert it from an object to string with stringify
var json = JSON.stringify(obj);
//use fs to write the file to disk
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback);
if you want to append it read the json file and convert it back to an object
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
}});
Complete Code:
// POST to add a task
app.post('/task', function(req, res) {
res.set('Content-Type', 'application/json')
var obj = {
table: []
};
obj.table.push({id: req.params.id , square: req.params.square});
var json = JSON.stringify(obj);
var fs = require('fs');
fs.writeFile('myjsonfile.json', json, 'utf8', callback)
fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
obj = JSON.parse(data); //now it an object
obj.table.push({id: 2, square:3}); //add some data
json = JSON.stringify(obj); //convert it back to json
fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back
// returns 201 on success
res.json({
code: 201,
message: 'Success'
});
}});
});
I have the following code:
serverside.js:
var express = require('express');
var app = express();
app.post('/LEDon', function(req, res) {
var obj = res;
console.log('LEDon button pressed!');
// Run your LED toggling code here
});
app.listen(1337);
clientside.js:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
data: JSON.stringify(test),
contentType: 'application/json'
});
});
view.html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='ledon-button'>LED on</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src='clientside.js'>
</script>
</body>
</html>
Nothing happens when I click the button. But if I remove some lines from clientside.js it works:
$('#ledon-button').click(function() {
var test = "123";
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
});
});
But this way no JSON-file is being sent. I tried looking at tutorials but found nothing. What am I missing?
So this is how I solved it:
clientside:
function getData(number) {
var teamId = number; // in data!!
$.ajax({
type: "POST",
url: "http://localhost:80/getdata",
crossDomain:true,
dataType: "json",
data:JSON.stringify(teamId)
}).done(function ( data ) {
var myJSON = JSON.stringify(data);
}
server side:
var express = require('express');
var app = express();
// Load the http module to create an http server.
var http = require('http');
const mysql = require('mysql');
app.post('/getdata', function(request, response) {
var store = '';
var query;
var query2;
// First you need to create a connection to the db
const con = mysql.createConnection({
host: 'db.host.net',
user: 'dbuser',
password: 'mypw',
database: 'dbname',
});
request.on('data', function(data) {
store += data;
query = "regular db query";
con.connect((err) => {
if (err) {
console.log('Error connecting to Db');
return;
}
console.log('Connection was established');
});
con.query(query, (err, rows) => {
if (err) throw err;
// handling query stuff
query2 = "regular db query";
// getting db query
con.query(query2, (err, rows2) => {
// handling query stuff
if (err) throw err;
myJSON = {
"var1": "data1",
"va2": "data2"
}
console.log("\nThe JSON resultset: " + JSON.stringify(myJSON));
response.end(JSON.stringify(myJSON));
con.end();
});
});
console.log("DB connection ended");
});
request.on('end', function() {
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
});
}); app.listen(80);
Let me know if something is unclear or can be done better.
I'm currently learning JavaScript / NodeJS / electron, and I want to build a small presenter-app to remotely control powerpoint-presentations.
I've setup a server using electron like this:
const electron = require('electron');
const robot = require("robotjs");
const fs = require('fs');
const express = require('express');
const cors = require('cors');
const {
app,
BrowserWindow
} = electron;
var mainWin = null;
var contentString;
app.on('ready', function() {
mainWin = new BrowserWindow({
width: 800,
height: 600
});
contentString = "";
// Remove Menu-Bar
mainWin.setMenu(null);
const port = 3000;
var app = express();
app.use(cors());
app.post('/remote/forward', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - forward");
robot.keyTap("right");
});
app.post('/remote/backward', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - backward");
robot.keyTap("left");
});
app.listen(port, function() {
log(mainWin, 'server listening on port ' + port);
});
});
function log(mainWin, text) {
contentString += getFormattedDate() + " " + text;
contentString += "<br />";
mainWin.loadURL("data:text/html;charset=utf-8," + encodeURI(contentString));
}
I call these with two js-functions:
function sendForwardRequest() {
$.ajax({
type: 'POST',
data: {
blob: {action:"forward"}
},
contentType: "application/json",
dataType: 'json',
url: 'http://192.168.2.110:3000/remote/forward',
success: function(data) {
console.log('success');
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
}
function sendBackwardRequest() {
$.ajax({
type: 'POST',
data: {
blob: {action:"backward"}
},
contentType: "application/json",
dataType: 'json',
url: 'http://192.168.2.110:3000/remote/backward',
success: function(data) {
console.log('success');
},
error: function(error) {
console.log("some error in fetching the notifications");
}
});
}
I'm sure that this solution is quite miserble, as I said, I'm currently learning this. My question now is: This works for exactly seven times. After that, I have to reload my clients browser. How can I fix this? Also, what would be a better solution for the requests? I'd like to have only one app.post()-method and use the given post-parameters instead. Last question: What could be a nicer method for the logging? I'd like to append content to my window instead of having to reload the whole string each time.
Thank you very much!
this is the minified version of your code. try and see if it still only fires 7 times
/* Server side */
// instead of two app.post functions, use this one
app.get('/remote/:key', function(request, response, next) {
var ip = getRemoteIP(request);
log(mainWin, "presenter - " + request.params.key);
robot.keyTap(request.params.key);
response.send(request.params.key + ' key pressed');
});
/* Client Side */
function sendKey(key) {
return $.get('http://192.168.2.110:3000/remote/' + key)
}
// to send right key
sendKey('right').done(function(response) { /*success*/ }).fail(function(error) { /*error*/ });
I am trying to write a small authentication service using Express and Node.
I did a search on SO and don't seem to find my answer
even though there're many similar questions but no
definitive answer really.
I tried many variations of my server side code but
seems I am still missing something.
The POST call is made from an HTML page
with some JQuery code (ajax call).
I enter the post() method in Express but when
it returns response to the HTML page, always the ajax
error handler is executed, never the success handler.
My JSON which I return seems valid to me.
I tried calling send and json on the
response object but nothing really works.
What am I missing?
Any help would be greatly appreciated.
Thanks in advance.
var mod = require('express');
var auth = require('./login_module.js'); // my module
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/login', function(request, response) {
console.log("post method called");
var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials);
auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
console.log("Response Code: " + code);
var res = {
data : "Response Code: " + code
};
console.log(JSON.stringify(res));
// So far I am good!
response.statusCode = code;
response.json(res);
// Response is now sent
// but not recognized as
// valid JSON in the client.
console.log("response sent");
});
});
app.listen(10101);
JQuery call.
<script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
alert('calling now!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
alert('got response back!');
if ("200" === textStatus){
$('#status').text('Login succeeded!');
}else if ("401" === textStatus){
$('#status').text('Login failed!');
}else{
$('#status').text('Invalid status received: ' + textStatus);
}
},
error : function(jqXHR, textStatus, errorThrown){
alert("Error when getting response.");
},
dataType: 'json'
});
})
});
</script>
As adeneo pointed out the key was to serve the html page over
http and not over file protocol. The rest was just some tuning
of various details about the Ajax jQuery call.
Server-side code:
var mod = require('express');
var auth = require('./acct_module.js');
var fs = require('fs');
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/login', function(request, response) {
console.log("POST called - try to login against the MongoDB.");
var credentials = request.body;
console.log("credentials = " + credentials);
console.log(credentials.username);
console.log(credentials.password);
auth.authenticate(credentials.username, credentials.password, function(result){
console.log("Authentication Result: " + result);
var code = result === 1 ? 200 : 401;
var message = result === 1 ? "Login succeeded!" : "Login failed!";
console.log("Response Code: " + code);
var res = {
message: message,
code : code
};
console.log(JSON.stringify(res));
response.statusCode = code;
response.json(res);
console.log("POST response sent.");
});
});
app.get('/login', function(request, response){
console.log("GET called - send back the HTML file.");
fs.readFile('login.html', function (err, data) {
if (err) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("Request failed.");
response.end();
return;
}
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
console.log("GET response sent.");
});
});
app.listen(10101);
Login page login.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$( "#btn" ).click(function(){
// alert('Now calling the auth manager!');
var obj = {
username: $('#usrn').val(),
password: $('#pwd').val()
};
$.ajax({
type: "POST",
url: 'http://localhost:10101/login',
data: obj,
success: function (data, textStatus, jqXHR){
// alert('success called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
error : function(jqXHR, textStatus, errorThrown){
// alert('error called!');
var res = JSON.parse(jqXHR.responseText);
$('#status_message').html(res.message);
$('#status_code').html(res.code);
},
dataType: 'json'
});
})
});
</script>
</head>
<body>
<input type="text" id="usrn" name="usrn"/><br>
<input type="password" id="pwd" name="pwd"/><br>
<input type="button" id="btn" name="btn" value="LOGIN!"/><br><br>
<div id="status_message" name="status_message"></div><br>
<div id="status_code" name="status_code"></div><br>
</body>
</html>
This does what you're looking for: https://github.com/braitsch/node-login
I'd recommend grabbing that from git and looking through it. You could even use it as a template. Pretty good stuff, and when you want to see the client side of things you can just look at the scripts associated with the login page.
example here:
http://node-login.braitsch.io/