0

On form submission I would like to stay on the same page and display a message (either success or failure). The HTTP POST request is handled as follows:

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

In the client side .ejs file I then try to use ajax to display the alert (I tried following the example from how to use NodeJS pop up a alert window in browser) as follows:

    <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 issue is that when I press the submit button it takes me off the page and displays: ```{"success":true}`` instead of staying on the same page after the form submission and displaying a popup with the status of the request.

NicLovin
  • 317
  • 3
  • 20
  • 3
    You need to disable normal form submission with `event.preventDefault()`. – Barmar Oct 12 '21 at 16:07
  • I think the issue here is that the AJAX request will fire on page load as it is not bounded to any event listener or within any function. Without seeing the configuration of the form in question however, it is quite literally impossible to give any concrete answer specific to your scenario. – esqew Oct 12 '21 at 16:11

1 Answers1

0

see here: Prevent redirect after form is submitted

you need to add return false; to the end of your AJAX request :)

Evander
  • 57
  • 4