Redirect to new page after AJAX post request using express - javascript

I need to make a button that on click redirects me to a new page (localhost:1337/LEDon) and logs some data to the console. However, I can't get the button click to load a new page.
Here's my code -
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/view.html');
});
app.post('/LEDon', function(req, res) {
console.log('LEDon button pressed!');
res.sendFile(__dirname + '/success.html');
});
app.listen(1337);
clientside.js
$('#ledon-button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon'
});
});
view.html
<!DOCTYPE html>
<head>
</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>
success.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Success page</title>
</head>
<body>
LEDon button pressed!!
</body>
</html>

$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon',
success:function(data, code, jqXHR) {
window.location.pathname = "success.html"
}
});
and your node:
app.post('/LEDon', function(req, res) {
console.log('LEDon button pressed!');
res.status(200)
res.sendFile(__dirname + '/success.html');
res.end()
});
Is one way of doing it, provided this is the only functionality you want for it. Otherwise you can send a 3XX HTML Status code and the browser will deal with it for you, I believe

Related

Node.js Express.js Send Jquery Ajax Post throws Constant Error - I'm stuck

I'm trying to make a very simple return coming from Node.js to Ajax. I'm using Express.js to make this possible.
I have code from the previous route that I did in order to write and manage JSON files and it works just fine.
The problem comes from the second route that always throws an error when I'm trying to make it return something with the JQuery ajax success method. It is the most simple form of send that I found but still doesn't work.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test 2</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</head>
<body>
Cod: <input type="text" name="cod" id="cod">
Text: <input type="text" name="text" id="text">
<button id="boton">PRUEBA</button>
<button id="getText">GET TEXT</button>
<script>
$('#boton').click(function() {
let cod=$('#cod').val();
let text=$('#text').val();
console.log(cod);
console.log(text);
$.ajax({
type: 'POST',
data: {
cod: cod,
text: text,
},
url: 'http://localhost:1337/prueba'
});
});
$('#getText').click(function() {
$.ajax({
type: 'POST',
data: {
},
success: (result) => {
console.log(result);
},
error: (result) => {
console.log('ERROR');
},
url: 'http://localhost:1337/getText'
});
});
</script>
</body>
</html>
app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/prueba', function(req, res) {
// ... First Route. The code here works just fine so I don't add it here.
});
app.post('/getText', function(req, res) {
let text = "Hola mundo";
console.log(text);
res.send(text);
});
app.listen(1337, () => console.log('Started server at http://localhost:1337!'));
When you click the 'GET TEXT' Button it enters inside the '/getText' route in app.js and console.logs the text on the node.js terminal so that's not the issue.
The issue seems to come from the res.send() function.
In the browser console it logs 'ERROR' as it appears in the ajax error method associated to the 'GET TEXT' Button. I can't find a way to make it return success.
Could anyone help me? I'm so stuck with this project for work.
looks like a CORS issue... do you serve index.html from the same location?
It works serving index.html from node
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/prueba', function(req, res) {
// ... First Route. The code here works just fine so I don't add it here.
});
app.post('/getText', function(req, res) {
let text = "Hola mundo";
console.log(text);
res.send(text);
});
app.get('*', function (req, res) {
res.sendFile('index.html', {root: '.'})
})
app.listen(1337, () => console.log('Started server at http://localhost:1337!'));
There are several options for node/express, e.g. express middleware

Uncaught Syntax Error: Unexpected token (First program)

Uncaught SyntaxError: Unexpected token <
Calling a javascript with console.log ("hello world");
I'm codding my first steps in the node, without any framework at the beginning to understand the main and simple aspects of node.js
I just created my server in Node.js (main.js) and calling an index.html, this index.html call a sayHi.js, it only has a console log. But this script not works...
I would like to do a controller/script to this HTML file to start programming...
//main.js
var http = require("http");
var fs = require("fs");
var url = require('url');
//create a server object:
http.createServer(function(req, res) {
if (req.url === "/index" || req.url === '/') {
fs.readFile('app/views/index.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
} else if (req.url === "/modbus") {
fs.readFile('app/views/modbus.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
} else {
fs.readFile('app/views/404.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
}
})
.listen(8080); //the server object listens on port 8080
console.log('Server running at http://127.0.0.1:8080');
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../scripts/sayHi.js"></script>
<!-- <link rel="stylesheet" href="/app/styles/myStyle.css" /> -->
</head>
<body>
<h1>Hello! Now you know how to serve HTML files using Node.js!!!</h1>
<p id="demo"></p>
Modbus
</body>
</script>
</html>
//sayHi.js
console.log("hello world");
Uncaught SyntaxError: Unexpected token <
The first thing I would point out is that your HTML file is looking for a javascript file under the name of sayHi.js, from ../scripts/sayHi.js path.
Your Html file is served at http://localhost:8080/ and tries to get http://localhost:8080/scripts/sayHi.js to which you have no route, so the server.js will try to send the error html, which is in 404.html file.
this is an HTML file, but is injected as a javascript file, which will result in the console error in the browser.
My suggestion is to return appropriate status code, i.e. 404, in the header, and build a route to the sayHi.js in your server file.
Remove the script tag </script> above html tag </html>.
Change the following code from this:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../scripts/sayHi.js"></script>
<!-- <link rel="stylesheet" href="/app/styles/myStyle.css" /> -->
</head>
<body>
<h1>Hello! Now you know how to serve HTML files using Node.js!!!</h1>
<p id="demo"></p>
Modbus
</body>
</script>
</html>
To this:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../scripts/sayHi.js"></script>
<!-- <link rel="stylesheet" href="/app/styles/myStyle.css" /> -->
</head>
<body>
<h1>Hello! Now you know how to serve HTML files using Node.js!!!</h1>
<p id="demo"></p>
Modbus
</body>
</html>
else if(req.url === "/sayHi"){
fs.readFile('/app/scripts/sayHi.js', function (err, data) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
#reza
How can I do this?
My suggestion is to return appropriate status code, i.e. 404, in the header, and build a route to the sayHi.js in your server file.
Thank you so much for your help:
This sentence helped me: My suggestion is to return appropriate status code, i.e. 404, in the header, and build a route to the sayHi.js in your server file.
Solution

successful server response without executing the Ajax route in NodeJs / Express

I register my login route
app.use('/login', require('./routes/login'));
and this module contains the route to render my login HTML page and the Ajax call validating the login.
var router = require('express').Router();
router.get('/', function (req, res) { // render login HTML page
res.render('login');
});
router.post('/validateLogin', function (req, res) { // Ajax call - login button pressed
var data = req.body;
var username = data.username;
var password = data.password;
var loginIsValid = true; // TEST
var session = req.session;
session.user = { // TEST
userId: 0 // TEST
};
res.send({
isValid: loginIsValid
});
});
module.exports = router;
The client has a login button. This button executes an Ajax call to the server. If the login is valid the user should get redirected to another page.
function login() {
$.ajax({
type: 'POST',
url: 'validateLogin', // Ajax route name
contentType: 'application/json',
data: JSON.stringify({
username: $("#edtLoginUsername").val(),
password: $("#edtLoginPassword").val()
})
}).done(function (response) { // server response
if (response.isValid) { // valid login?
// redirect the user to another page
} else {
alert("invalid login");
}
}).fail(function () {
});
}
The code always results in "invalid login". I started debugging response. This variable returns my full HTML as a string. It's not the correct response object from the server.
I created a console.log in my Ajax route and this route never gets called.
The client does not throw the "not found" error and gets a successful response even when not calling the route on the server?
As I said the response is not correct, it just contains my full HTML page as a string.
Edit
The response object contains
"<!DOCTYPE html> <html> <head>
<meta charset="utf-8">
<title></title> </head>
<link href="/style/base.css" rel="stylesheet"> <link href="/style/header.css" rel="stylesheet"> <link href="/style/button.css" rel="stylesheet"> <link href="/style/input.css" rel="stylesheet"> <link href="/style/link.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<body>
<link href="/style/templates/login.css" rel="stylesheet">
<script src="/client/templates/login.js"></script>
<div id="pageContent">
<div id="loginContainer">
<img id="logo" src="/resources/logo/img_logo_big.png">
<div id="frmLogin">
<div id="frmLoginHeader">
<p id="loginHeaderTitle">Login</p>
</div>
User
<input class="edt" id="edtLoginUsername" type="text" placeholder="Username">
Password
<input class="edt" id="edtLoginPassword" type="password" placeholder="Password">
<button class="btn" id="btnLogin">Login</button>
</div>
</div> </div>
</body> </html> "
you create a route prefix to login all your routes now are under "/login"
so you can change your ajax url to
url: 'login/validateLogin', // Ajax route name
or you can change you prefix
app.use('/', require('./routes/login'));
and to get the login page do
router.get('/login', function (req, res) { // render login HTML page
res.render('login');
});

How do I get an image from a folder using Ajax and Nodejs?

So, I want to upload a picture and show it right below the page so it looks like I am "posting" the picture.
So here's what I did in NODEJS:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/img');
},
filename: function (req, file, cb){
cb(null, file.originalname);
}
});
var upload = multer({storage: storage});
app.post('/', upload.single('file'), function(req, res){
res.send(req.file);
});
So right now every time I upload a picture it goes right into the folder called 'img'.
Now I want to retrieve this img using ajax and that's what I did in JAVASCRIPT:
$("input[type=submit]").click(function(){
$.ajax({
type: 'POST',
url: '/',
success: function(data){
console.log(data);
}
});
});
However, I don't get anything from the success function in ajax, rather, I just go to another page where I can see this json:
{
fieldname: "file",
originalname: "extensao.jpg",
encoding: "7bit",
mimetype: "image/jpeg",
destination: "./public/img",
filename: "extensao.jpg",
path: "public/img/extensao.jpg",
size: 411576
}
How can I make this work and receive this JSON in my success function? I thought by doing res.send(req.file) I was already sending the data to my ajax request.
after you've saved the images, you can get them by using this piece of code. This will send the file to the user. Let's say you have a file named jeff.jpg inside ./public/img all you have to is to go to yourlink.com/files/jeff.jpg to retrieve it.
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + 'public/img/' + req.params.filename);
})
This means that you can also render the images in your html by only using img tag. For example,
<img src="./public/img/jeff.jpg"/>
This is the whole code to my main.js file,
var express = require('express')
var multer = require('multer')
var app = express();
var whereFilesAreStored = '/public/img';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, __dirname + whereFilesAreStored) //you tell where to upload the files,
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
var upload = multer({storage: storage,
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...')
},
});
app.set('view engine', 'ejs');
app.get('/', function(req, res, next){
res.render('mult'); //our html document
})
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + whereFilesAreStored + '/' + req.params.filename);
})
//file upload
app.post('/post', upload.single('file'), function (req, res, next) {
console.log(req.file);
return false;
})
app.get('/ajax', function(req, res){
res.render('ajax');
})
To use the images in the client side, I have made a file named ajax as you can see above. this is my html.
Using ajax at this point is useless, it is only used to check if there's any updates on a page. But still I have made a small code for ajax for you to see. Don't use ajax for this task. you can use <img src="thelink"/> to get the file to your page. Please check my img tag down below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Anasayfa</title>
<link type="text/css" rel="stylesheet" href="/cssDosyalari/ana.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
var theUrl = 'http://localhost:2222/files/';
var fileName = "jeff.jpg";
var wholePath = theUrl + fileName;
$.ajax({
type: 'GET',
url: wholePath + fileName,
success: function(data){
console.log(data);
}
});
</script>
<img src="http://localhost:2222/files/jeff.jpg" alt="">
</body>
</html>
UPDATE
I have had problems with using ajax to it. Some reason, the link redirects me, so I have came up with this solution. I send the ajax, the server uploads the file, then makes the client reload the page with the image coming out. I am using ejs + ajax in here. Please check the code down below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
$('#my-form').submit( function(e) {
e.preventDefault();
//function myFunc(){
$.ajax({
url: '/post',
data: $('#myFile'),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
})
e.preventDefault();
console.log('ajax sent');
return false;
// }
}
//onclick="myFunc()"
</script>
<form id="my-form" action="/post" method="post" enctype="multipart/form-data">
<input id="myFile" type="file" name="afile" value="">
<input type="submit" name="" value="submit">
</form>
<img id="theImgSrc" alt="">
<script type="text/javascript">
$( document ).ready(function() {
$('#theImgSrc').attr('src', 'http://localhost:2222/files/<%=fileName%>').load();
});
</script>
</body>
</html>
This is my main.js file,
app.get('/files/:filename', function(req, res){
res.sendFile(__dirname + whereFilesAreStored + '/' + req.params.filename);
})
app.get('/', function(req, res, next){
res.render('mult', {fileName: ''}); //our html document
})
app.post('/post', upload.single('afile'), function (req, res, next) {
res.render('mult', {fileName: req.file.originalname});
console.log(req.file);
})

How to build client server app using node js and html?

I have html file called temp.html
I want to display select query result in that html page.
This is my select query.
SELECT cs_name FROM course_master where cs_id = 4
This query will return following result.
[ { cs_name: 'JAVA programming' } ]
I want to display this result in html page.
Basically I want to use the "GET" request and response using node js.
This is my node js file structure.
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'eduportal'
});
connection.connect();
connection.query('SELECT cs_name FROM course_master where cs_id = 4', function(err, rows, fields) {
if (!err)
console.log('The solution is: ', rows);
else
console.log('Error while performing Query.');
});
connection.end();
This is my HTML file.
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
</head>
<body>
<div id="course_name">
Course Name:<input type="text" id="cname">
</div>
</body>
</html>
I want to display course name in text box which I defined in HTML file.
Can anyone help to bind this text box with mysql using node js?
You can achieve this by socket.io. You need to learn more about this to understand following snippet.
In this i have provided a sample code to full fill your requirement.
Might be possible that some tweaks still in this code so you can change those by your understanding.
Let me clarify about following server.js snippet
In this you can put your all queries to get or set in db.
//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.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'eduportal'
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket) {
console.log("A user is connected");
get_cs_name(function(res,cs_name) {
if (res) {
io.emit('get_cs_name', cs_name);
} else {
io.emit('error');
}
});
});
var get_cs_name = function(callback) {
pool.getConnection(function(err, connection) {
if (err) {
connection.release();
callback(false);
return;
}
connection.query("SELECT cs_name FROM course_master where cs_id = 4", function(err, rows) {
connection.release();
if (!err) {
callback(true,rows[0].cs_name);
}
});
connection.on('error', function(err) {
callback(false,null);
});
});
}
http.listen(3000, function() {
console.log("Listening on 3000");
});
Now run "node server.js" command from CLI. Your http request will be handle on 3000 port. please keep this in mind.
//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();
socket.on('get_cs_name',function(cs_name){
alert(cs_name);
$("#cname").val(cs_name);
});
});
</script>
</head>
<body>
<div id="course_name">
Course Name:<input type="text" id="cname">
</div>
</body>
</html>
Now its time to browse your html file to see your actual result that it is working or not, please hit http://localhost:3000 in browser.
If any error found please ping me back here.
Thanks

Categories