简体   繁体   中英

Show a success message after PHP form submission using AJAX

I have a newsletter sign up in a bootstrap modal.

What I am trying to achieve is when a client submits their email, it should give a success message in the modal directly underneath, on the same page without redirecting to a new page.

I am new to AJAX so just some direction would be helpful.

Here is my HTML code

<form form id="form1" name="form1" method="post" action="process.php">
    <div class="input-group">
        <input class="btn btn-lg" name="email" id="email" type="email" placeholder="Your Email" required/>
        <button type="submit" class="button">Submit</button>
    </div>
</form>

And below is process.php

/* Database config */
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'maxipakdb'; 
/* End config */

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
}

$email = $_POST['email'];

// Perform queries 

mysqli_query(
    $mysqli,
    "INSERT INTO maxipaktable (id,email) VALUES (NULL,'$email')"
);

echo $email;

检查此链接: https : //api.jquery.com/jquery.post/ Ajax Post方法是您所需要的,并且实际上很容易理解。

Remove form name, action from html.

<form form id="form1">
    <div class="input-group">
        <input class="btn btn-lg" name="email" id="email" type="email" placeholder="Your Email" required/>
        <button type="submit" class="button">Submit</button>
    </div>
</form>

<!-- The result of the success message rendered inside this div -->
<div id="result"></div>

/* Attach a submit handler to the form */

 $(document).ready(function() {
 $("#form1").submit(function(event) {
         var ajaxRequest;

        /* Stop form from submitting normally */
        event.preventDefault();

        /* Clear result div*/
        $("#result").html('');

        /* Get from elements values */
        var values = $(this).serialize();

        /* Send the data using post and put the results in a div */
        /* I am not aborting previous request because It's an asynchronous request, meaning 
           Once it's sent it's out there. but in case you want to abort it  you can do it by  
           abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
           ajaxRequest= $.ajax({
                url: "process.php",
                type: "post",
                data: values
            });

          /*  request cab be abort by ajaxRequest.abort() */

         ajaxRequest.done(function (response, textStatus, jqXHR){
              // show successfully for submit message
              $("#result").html('Submitted successfully');
         });

         /* On failure of request this function will be called  */
         ajaxRequest.fail(function (){

           // show error
           $("#result").html('There is error while submit');
         });

       });

first, change your button submit to <button onclick='javascript:ajaxpost();'>Submit</button> to prevent for manually submit without ajax

second, put your success modal bootstrap with id (eg id = modalnl)

third, put the codes below to your html file

function ajaxpost(){
    $.ajax({
        url: "process.php",
        type: 'POST',
        data: $('#form1').serialize(),
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        },
        success: function(data){
            $('#modalln').show();
        }
    });
}
**Here is code for ajax. Remove action**
<form form id="form1" name="form1" method="post">
    <div class="input-group">
        <input class="btn btn-lg" name="email" id="email" type="email" placeholder="Your Email" required/>
        <button type="submit" class="button" id="contactform">Submit</button>
    </div>
</form>
<script type="text/javascript">
$("#form1").submit(function(e) {
  $.ajax({
         type: "POST",
         url: process.php,
         data: $("#contactform").serialize(), // serializes the form's elements.
         success: function(data)
         {
             $("#form1").html("<p>Thank you</p>");
         }
       });
  e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM