Navigating to another webpage after sending an AJAX post request with the help of Express

I am trying to create a button that, when clicked, will take me to a new page (localhost:1337/LEDon) and also log some data to the console. However, I'm having trouble getting the button click event to load the new page.

Below is the code I have been working with:

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>

Answer №1

$.ajax({
        type: 'POST',
        url: 'http://localhost:1337/LEDon',
        success:function(data, code, jqXHR) {
            window.location.pathname = "success.html"
        }
});

In addition, you can implement the following for your node:

app.post('/LEDon', function(req, res) {
  console.log('LEDon button pressed!');
  res.status(200)
  res.sendFile(__dirname + '/success.html');
  res.end()
});

If this is all the functionality needed, it should suffice. Otherwise, consider utilizing a 3XX HTML Status code and let the browser handle the redirection for you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Flask Serenade for Express JS

Is there a module similar to Python Flask Restful's marshal for Node/Express? I need something that allows me to put an object into a function and send it with good attributes as a JSON object. If you know of any such module or solution, please let ...

Serve files from a project root directory using Express.js

Looking to extract my node.js/express.js UI (html/resources) from the current project directory. Essentially, I want to relocate all of my static files such as html/js/css into a separate directory above the project directory. Example: rootpath /UI ...

Divide the Elements and Insert Them into an Empty JavaScript Array

Imagine an empty array named result[]. Now, picture a scenario where a user clicks on a link triggering a function named getId(), which passes the clicked id to be matched against another array called productsArray[]. <a href="javascript:void(0)" class ...

My form submission is getting messed up by VueJS, causing it to delete all of the data

It seems that VueJS is causing issues with my form submission process, as it is removing the post data from the Ajax serialize() function. I suspect it could be due to the combination of using Ajax and Jquery, but I'm unsure how to resolve this issue ...

The underscore convention for defining members in Typescript allows for clear and concise

Let's talk about a class called Email class Email { private _from: string; private _to: Array<string>; private _subject: string; } When an email object is created, it will look something like this: { _from:'', _to:'&apo ...

Preventing non-breaking spaces and characters from being added in Jquery Mobile

When developing an application using jQuery Mobile, I encountered a strange issue on my homepage. In between the listview, this code snippet appeared: &nbsp;&nbsp;&nbsp;&nbsp; But without the following meta tag: <meta http-equiv="Cont ...

What could be the reason behind the app.get middleware not functioning properly following the app.use middleware in ExpressJS?

My server.js file includes the following code. However, I've encountered an issue where the code in app.get() function works fine when the app.use() middleware is commented out. But, when both are included, the get request doesn't seem to run. An ...

Determine the central point between two nodes, then sketch a line at a 90-degree angle extending from it to create a new node

Imagine in d3 there are two nodes, node1 and node2, depicted as circles positioned next to each other horizontally. These nodes are connected by a short horizontal line (represented as a path). I am curious about how to: (1) determine the midpoint of that ...

When inserting an <a> tag into the code, an issue arises with the image slide show

I currently have a single image slideshow on my website implemented with the following JS code: function slideSwitch() { var $active = $('#slideshow IMG.active'); if ($active.length == 0 ) $active = $('#slideshow IMG:last'); ...

What steps can I take to repair broken links in a Bootstrap template?

I am currently working with the startbootstrap-bare template from Blackrock Digital. My goal is to have different content load when a user clicks on the About link (about.html), while still keeping the navigation menu intact. However, when I change the hr ...

How do I incorporate core functions into Angular services and controllers within my app?

(ANGULAR-JS) I am working with a function called locationChange(x, y) that has two arguments and is located in core/services. var locationChange = function(x, y) { return new Promise(function(resolve, reject) { --- Now, I need to utilize th ...

Making an Ajax request using flask-seasurf

Currently in the process of developing a small app on localhost, I have implemented flask-seasurf to prevent csrf attacks. Most of my non-ajax forms are functioning properly with flask-seasurf. However, there is one form that triggers an ajax call to &apos ...

Steps to divide input form data and transmit it to MySQL

I am currently facing a challenge with my form, as it works perfectly when making calls to the server. However, I would like to enhance its functionality by allowing it to handle multiple input codes submitted by users. My main question is how can I modi ...

The node server is experiencing difficulties connecting to the mysql database, resulting in a timed out connection error at Connection._handleConnectTimeout

Having trouble establishing a connection with the mysql database. Every time I attempt to start the node server, it keeps throwing a database connection error. The specific error message is as follows: connect ETIMEDOUT at Connection._handleConnectTimeou ...

Disabling dates in Fullcalendar with AJAX for Machines and Users

Our software utilizes multiple jQuery fullcalendars on a single page for machine scheduling purposes. Each calendar triggers an AJAX call when a specific input related to the workload changes. The AJAX script is responsible for calculating disabled dates o ...

Managing data with Express Router for updating and deleting information

I am currently facing challenges with implementing CRUD functionality in my web application. The data is successfully stored in MongoDB on the cloud using a form, and I have managed to display the data to the user. However, I am struggling with updating an ...

I am experiencing an issue where the Axios configuration does not display the OnUploadProgress on my response

I have been attempting to track the progress of file uploads from the front end, but I am encountering an issue where the onUploadProgress is not being received in the configuration catch. This problem arises as I am relatively new to using Axios. axios({ ...

Does three.js have a MoveTo feature available?

As a beginner in three.js, I'm looking for a function similar to Unity's move towards in order to move objects from their current position to a specific Vector3. Any suggestions or insights on how to achieve this would be greatly appreciated. Tha ...

Parents are not visible when hiding or showing siblings

I've implemented a simple in-page search feature that displays topics containing the searched words. Each section includes a heading in <h2> tags, and I want these headings to be visible for unhidden blocks. The issue: The h2 header doesn&apos ...

The issue with fancybox links not functioning properly within ajax content

I'm looking to constantly update a specific section on my website using ajax, jquery, and php. Upon the initial page load, a javascript function is triggered to display the content of that section. Subsequently, json is utilized to check for any new ...