Tips for remaining on the current page after sending a post request using Express

I have a simple question that I haven't been able to find a satisfactory solution for. I've created a post route using express, like this:

app.post('/search', function(req, res){
    // Code to extract data from req and save it to the database
    // Want to stay on the current page afterwards.
});

Here's my html form:

<form action="/search" method="post">
     <input value="name" name="marker[name]">
     <input value="address" name="marker[address]">
     <input value="rating" name="marker[rating]">

     <button id="favo-button" type="submit">
         Submit
     </button>
 </form>

When the user clicks the submit button, the data is sent through req to the post route and inserted into the database. However, I want the page to remain on the current page. I've tried a few approaches but none have worked well. Here's what I've attempted:

  1. In the route,
res.render('/search');

This causes the page to re-render with the same view, but there's a flashing effect due to the re-render.

  1. Not doing anything with res in the route results in the page loading circle never stopping.
app.post('/search', function(req, res){
    var data = req.body.marker;
    // Some code to insert data into the database
    // Then do nothing with res. The page stays but keeps loading.
});

Is there a way to simply do nothing with res and stay on the page without the loading issue?

Answer №1

There are a couple of methods for accomplishing this task.

  1. To achieve this, you can send a 204 No Content response. (For example in Express:
    app.post('/search', (req, res) => res.status(204).send());
    , but this is basic HTTP functionality that can be implemented in any server-side code)
  2. Alternatively, you can use JavaScript to make the request (such as Ajax, utilizing XMLHttpRequest) instead of traditional form submission

(Another approach would be submitting the form to a hidden iframe, although this is considered an inelegant solution).

Answer №2

If you want to achieve this task, there are two methods you can use:
1 - Utilize Jquery AJAX call, ensuring to implement the code in your view page rather than in the controller or route of your NODEJS App.

$("#YOUR_FORM_ID").on("submit", function () {
    $.ajax({
        url: '/search',
        type: 'POST',
        cache: false,
        data: { $("#YOUR FORM ID").serialize() },
        success: function (data) {
            alert('Success!')
        }
        , error: function (jqXHR, textStatus, err) {
            alert('text status ' + textStatus + ', err ' + err)
        }
    });
});

2 - Redirect the request back to its original source

app.post('/search', function(req, res){
   //Do Something
   res.redirect('/');//redirect to the page from where request came
});

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

Converting HTML content into a single string simplifies data manipulation and extraction

exampleHTML=" This is sample HTML code that needs to be converted into a string using JavaScript </p>" I am looking to transform it into a single string format like str="This is sample HTML code, that needs to be converted into a string ...

I am struggling to link my JS application with a PHP file as it is showing "PHP file not found

I am facing an issue with my JS application. I am unable to send data from jQuery to a PHP file, as I encountered this error message: POST https://magazyn.rob-tech.pl/savesettings.php 404 The app is running on PORT=8080 npm run start and the package.json ...

The ajaxStart event does not seem to be triggering when clicked on

I am having trouble adding a loader to my site using the ajaxStart and ajaxStop requests to show and hide a div. The issue is that these requests are not being triggered by button onclick events. <style> // CSS for loader // Another class with o ...

Show the checked items in the table based on the ID value stored in the array

When I click the button labeled Show checked if id values are 1 and 5, I encounter an issue in displaying checked items in the table based on their corresponding id value in the array. Essentially, I want to show the checked items in the table only if thei ...

Combining Json, Jquery Autocomplete, and PHP to customize the displayed search options based on multiple items within the Json data

I have a PHP file that returns an array of results, with the 'Name' field being one of them. I want to customize my jQuery autocomplete feature to only search by the 'Name' field and suggest results based on that. However, once a sugges ...

I'm curious, what is the optimal method for arranging a json object based on an index contained in each of its properties?

I'm working with an array of objects, looking like this myArray = [ { id: 3, data: foo }, { id: 7, data: bar } ] However, I would like to transform it into the following structure transformedArray = { 3: ...

What is the best way to adjust image size based on different screen sizes while ensuring the buttons at the top remain responsive

How can I make the image and image select and delete buttons responsive? I am looking to eliminate the gap after the delete button. Any suggestions are welcomed. <div class="container mt-0"> <div class="row"> ...

What is the best way to invoke a function in a class from a different class in Angular 6?

Below is the code snippet: import { Component, OnInit, ViewChild } from '@angular/core'; import { AuthService } from '../core/auth.service'; import { MatRadioButton, MatPaginator, MatSort, MatTableDataSource } from '@angular/mater ...

Fetch information from the database, Send it via AJAX to refresh the database, Then circle back to retrieve fresh data! Utterly perplexed

I am looking to retrieve data from a MySQL database using PHP and assign them to a JavaScript array. There are 200 records in my database, and I want to randomly select 10 records. $myQuery = mysql_query("select * from tblx where xyz=1 order by rand() lim ...

Script on the server side fails to execute following validation of form

Hey there, I'm struggling with my signup form. I want to submit the form using ajax after completing validation. I've used a jQuery plugin for validation, but whenever I click on any field, the ajax request is automatically sent to the server and ...

Step-by-step guide for implementing a scroll event on FancyBox

I am facing an issue with a large fancybox popup that contains a scroll function. I need to find a way to attach an event to this fancybox popup when scrolling. I have tried several different events, such as: $('.fancybox-inner').off("scrol ...

Creating a HTML5 canvas animation of an emoticon winking to add a fun touch to your

Currently, I am facing a challenge in animating an emoticon that was initially sketched on canvas. While following a tutorial to implement draw and clear animations using frames, I haven't been able to achieve the desired outcome. With 6 frames of the ...

What is the best way to connect my products on an ecommerce site with hundreds of images?

Despite thoroughly searching the internet, I have been unable to find a solution to my dilemma. I am creating a platform that showcases a lengthy list of products on the website. Additionally, I have a database of pictures stored locally that need to be ...

Tips for uploading information and posting it on a different page with mongoDB and Node.js

I am looking to implement a feature on a website where data is submitted to MongoDB from one page, and then retrieved and displayed on another page. The technologies I am working with include node.js, express, Mongoose, and MongoDB. Currently, the data is ...

The AJAX call in PHP is echoing JavaScript code that seems to be malfunctioning

Currently working on an AJAX page using php, where I plan to output a section of JS code upon completion. Despite having the JS code within the HTML page, it is not functioning properly. Any suggestions on how to get it to work? ...

Discover the process of integrating PWA features into an Express web application

I'm currently in the process of integrating PWA into a web application. I've created a manifest.json file and added it to the head of my page, which is loading correctly. However, the service worker registered in my app.js doesn't seem to be ...

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

Angular's $routeProvider fails to navigate

I'm facing an issue with my Angular JS application where the $routeProvider doesn't load the template in the ng-view section. I have set up <html data-ng-app="myApp"> and <section data-ng-view></section. The template doesn't ...

One of the three identical paths in Node.JS is experiencing issues

I'm brand new to Node.js and currently working on creating a backend api for a project. I have 3 routes in my application: societies, users, and emails. //module for email functionality emailsModule = require('./api/routes/emails')(co ...

Best Practices for Using require in Node.js

I have been working on an Express application where I am utilizing Mongoose for data storage. To ensure that my User model (featuring username and password) can be saved properly, I included require('mongoose') in the Models/user-model.js file. ...