Displaying Bootstrap alert after a successful jQuery AJAX call

I have been attempting to display an alert on a form once the submission action is completed.

Here is my JavaScript function:

    function submitForm(){

    // Initialize Variables With Form Content
    var nomeCompleto = $("#nomeCompleto").val();
    var email    = $("#email").val();
    var telefono = $("#telefono").val();
    var username = $("#username").val();
    var password = $("#password").val();
    var parametros = {
                  "nomeCompleto" : name,
                  "email"        : email

          };

          $.ajax({
                type: "POST",
                url: "adminRegistro.php",
                data: parametros,
                async:false,
                success: function(result){
                  var parsedData = JSON.parse(result);

                    $("#ajax-alert").addClass("alert alert-danger").text(parsedData.msg);
                    $("#ajax-alert").alert();
                    $("#ajax-alert").fadeTo(5000, 5000).slideUp(5000, function(){
                    });
                }
          });
}

The alert is triggered upon success, but it only shows for a brief moment (as if the page was reloaded). What am I doing wrong with my ajax call?

EDIT:

After some trial and error, I updated my HTML button code from:

<input class="btn btn-success submit-button" value="Submit"  onclick="myFunction()"/></input>
<input class="btn btn-success submit-button" value="Submit"  id=  "btnSubmit"/></input>

and adjusted the JavaScript:

$(document).ready(function (){

     $("#btnSubmit").click(function(){
     ....

This change resolved the issue. It appears that using

$("#btnSubmit").click(function(e){ e.preventDefault();
did not have any effect.

Answer №1

To prevent the default action, use the preventDefault() function. By calling this method within an event handler, you can cancel the default behavior associated with that event.

Here is an example of how to implement it:

function submitForm(e){

    e.preventDefault(); //This will prevent page reload
// Initialize Variables With Form Content
    var fullName = $("#fullName").val();
    var email    = $("#email").val();
    var phone = $("#phone").val();
    var username = $("#username").val();
    var password = $("#password").val();
        var parameters = {
            "fullname": name,
            "email": email

      };

      $.ajax({
            type: "POST",
            url: "adminRegister.php",
            data: parameters,
            async:false,
            dataType: 'json',
            success: function(parsedData){
                $("#ajax-alert").addClass("alert alert-danger").text(parsedData.msg);
                $("#ajax-alert").alert();
                $("#ajax-alert").fadeTo(5000, 5000).slideUp(5000, function(){
                });
            }
      });
 }

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

Creating PNG and JPEG image exports in Fabric.js with the help of Node.js

Exploring the wonders of Fabric.JS specifically designed for Node.JS, not intended for web applications, I've successfully created a Static Canvas and added a rectangle to it. Now, it's time to export the image. Take a look at my code snippet bel ...

Updating website content dynamically using AJAX and URL manipulation without refreshing the page (Node.js)

How can I update the inventory without refreshing the page using both button events and URLs? I want to be able to update to a specific page based on the URL parameter (like /inventory/2) when it is passed to the route. Currently, my AJAX request works but ...

Is it possible to input tab characters in a TextField?

I am working with a multi-line MUI TextField and my objective is to input JSON text. However, I encountered an issue where pressing the tab key causes the component to lose focus and shift to the next element on the page. Is there a way to prevent the ta ...

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

What steps are involved in developing a jQuery Validator function to enforce username restrictions?

Currently, I have implemented a method to enforce strong passwords like this: $.validator.addMethod('goodPassword', function(value, element){ return this.optional(element) || value.length >= 6 && /\d/.test(val ...

What causes Node's crypto module to generate varying outputs for identical strings?

I'm currently attempting to execute the following program: var crypto = require('crypto'); var a = crypto.createHash('md5').update('89Zr-J591').digest('hex'); var name = '89Zr−J591'; var b = crypto. ...

A guide on accessing information from a post form using an express.js server

Issue: Whenever the client submits a form using a post request to the server, the express server receives an empty body (req.body = {}). Objective: My goal is to retrieve req.body.username and req.body.password on a post request from the client (using the ...

The Django/Python function, toDataURL, outputs a response containing the string retrieved from the toDataURL method

I recently stored a string in a database that was returned by a javascript method called toDataURL. An example of the string can be found here: http://pastebin.com/0Qu8rngD My goal is to retrieve the image in a Django response. I've attempted various ...

Enhancing a Form Submission with Ajax

Working on a complicated form generated with Symfony2 and rendered using Twig and JQuery. This form is utilized to make modifications to e-commerce orders, therefore there's no clear submission process. How do I effectively sync the old form with the ...

Utilize a pipe to seamlessly transfer data from MSSQL to a Node.js application

I am currently utilizing node along with node-mssql version 6.0.1 for handling large amounts of data retrieval from the database and transmitting it to the frontend using streams. Although I have attempted to implement pipe and stream functionality as rec ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

Eliminate any duplicate items from the array containing objects

I've been struggling with this issue for a week now, hopefully someone here can help me out... The application I'm working on was created using Laravel with Vue for the frontend. Essentially, I have an array of objects that need to be sent to t ...

The API is providing data, but it's being returned within an ambiguous object. What could be causing this confusion?

Utilizing https and async for simultaneous calls to retrieve two objects, then storing them in an array. The call is structured as follows: if (req.user.isPremium == false) { // Free user - Single report let website = req.body.website0; let builtWit ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

Utilizing React-Router-Redux alongside the powerful features of React-Bootstrap

I've been struggling with this issue for some time now! My goal is to create a 'main app container' that consistently displays the logo, navigation... I plan on using react-bootstrap to enhance its appearance. Currently, I'm encounter ...

The provider for authentication, which is linked to the AuthenticationService and subsequently to the loginControl, is currently unidentified

Attempting to implement an authentication service in my application, I encountered an error when trying to call it within my controller: !JavaScript ERROR: [$injector:unpr] Unknown provider: AuthenticationServiceProvider <- AuthenticationService <- ...

Iterate over multiple form input variables using PHP

When I iterate through Rice form variables on the PHP side, everything functions properly. <input class="rice" type="text" name="rice[]" > <input class="beans" type="text" name="beans[]" > <input class="price" type="text" name="price[]" > ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...