Implementing AJAX functionality to dynamically show a message on a webpage following an HTTP POST request

After submitting the form, I want to remain on the current page and show a message indicating whether the submission was successful or not. The HTTP POST request is processed like this:

app.post('/insertdb', function(request, response) {
   // insert values from form into database
   response.json({success: true});
});

Then, in the client-side .ejs file, I attempted to use Ajax to display an alert message (following guidance from how to use NodeJS pop up an alert window in browser) as shown below:

<script>
      $.ajax({
        url: "/dbinsert",
        type: "post",
        data: 'testing',
        cache: false,
        success: function(response) {
          if(data['success']) {
            alert("success");
          }
          
        },
error: function () {
          alert("There has been an error");
        }
      });
    </script>

The problem arises when clicking the submit button as it navigates away from the page and shows: `{"success":true}` instead of staying on the same page post-form submission with a popup displaying the status of the request.

Answer №1

Check out this link for a solution: How to prevent redirection after submitting a form

To ensure the form does not redirect, remember to include return false; at the end of your AJAX request.

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

Unable to execute ajax on dom ready in Internet Explorer 9

Here is some code that needs to be executed on DOM ready without any user interaction: if($.browser.msie){ console.log("Using getJSON"); $.getJSON(baseUrl,function(){ alert('hi'); }); }else{ setTimeou ...

What is the process of incorporating HTML into a jQuery program in order to immerse the world in an element?

I am looking to utilize HTML with the value in a checkbox, After adding a shortcode: <label class="HCheck">(this is val 1 )</label> and incorporating jQuery to change it to: <label class="HCheck">(this is val 1 ) ...

What is the best way to duplicate an entire webpage with all its content intact?

Is it possible to copy an entire page including images and CSS using Selenium? Traditional methods like ctrl + a or dragging the mouse over the page do not seem to work. How can this be achieved with Selenium without requiring an element to interact with? ...

The D3 force layout is currently displaying just a single connection

I've been experimenting with a graph that I found in this demo and now I want to modify it to display data from Spotify. I created a sample JSON file and adjusted the script accordingly for the new data format, everything seems to be working fine exc ...

The GET request is returning a null array instead of the expected array contents

I am new to this, but I am trying to understand why my GET request is returning an empty array even though I am sure that the Mongo database collection is not empty. Each word form in the WordForm collection has a "lexicalform" key that refers to a Lexicon ...

Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading. Initially, I attempted to use a boolean variable that woul ...

Tips for getting Vue's element-ui validateField() function to function correctly in conjunction with v-if?

Kindly observe the password fields. The fields for 'Password' and 'Confirm Password' are displayed upon clicking on the 'Change Password?' button. The provided code functions properly and effectively validates the form using ...

Guide to capturing mouse drag coordinates using JavaScript within a JSP page

My task is to record the starting coordinates (x,y) and ending coordinates (x,y) of a mouse event. For example, on an HTML page with an image, users should be able to select a specific area by dragging the mouse. Therefore, I need to capture the coordinat ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

Develop a system using PHP and MySQL with corresponding mobile applications

I am in the process of developing a PHP eCommerce application with MySQL database as the backend. Additionally, I am looking to create a mobile application for this project. Which technology would be best suited for me to seamlessly develop both the Busin ...

Environment variables in Node process are uninitialized

I'm currently in the process of developing my first Express application, which requires interaction with an API using a secure API key. To ensure the security of this key and any future environment variables, I have decided to store them in a .env fil ...

What is the best way to retrieve a variable from MySQL in a Node.js environment?

var result; function getName(id) { //Retrieve name from database connection.query(`SELECT name FROM users WHERE id = "${id}"`, function (err, rows, fields) { if (err) console.log(err); result = rows[0].name; }); console.lo ...

When a function encounters an error, load a fresh page

I am facing an issue where I want to display a new error page whenever a function throws an error. The current situation is that when the getStockPoints function encounters an error and I handle it using try and catch block in app.js, the error is caught b ...

Updating the content of a file on an iPhone

Is there a way to update the entire document content with a response from an ajax request? I've tested out using document.body.innerHTML and document.write(), which both work on desktop Safari. However, I'm looking for a solution that will also ...

How to effectively filter a nested array in a Mongoose pre-find query

I am facing a particular issue. I have comments in my database that can be soft-deleted using a flag is_deleted. When this flag is set to true, it means the comment has been deleted. The comments are not stored as an independent model; instead, they are n ...

Refresh the array object following a personalized filter

I am currently using a custom filter to aggregate a $scope object within an ng-repeat block. Here is my code snippet: $scope.myobj = isSelected ? $filter('customFilter')($scope.origObj) : $scope.origObj In the above code, $scope.myobj is util ...

Autocomplete feature in Angular not showing search results

I am currently using ng-prime's <p-autocomplete> to display values by searching in the back-end. Below is the HTML code I have implemented: <p-autoComplete [(ngModel)]="agent" [suggestions]="filteredAgents" name="agents" (completeMethod)="f ...

Retrieving data from a radgrid with the power of jQuery

Trying to extract the text from the label GetName in a radgrid using jQuery. Need to iterate through each record to check the value of the label. Can anyone provide assistance? Thanks! Below is the code for my radgrid. <telerik:RadGrid ID="Gridview1 ...

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...