Reputation: 969
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>
Upvotes: 1
Views: 1714
Reputation: 919
$.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
Upvotes: 2