Innocent Monareng
Innocent Monareng

Reputation: 139

How to replace button with loading gif image when the submit button is clicked then on success remove form and replace with a success message

I have an html form and use the following codes to process it and verify input fields.

sendmail.php:

if($_POST) {

    // Enter the email where you want to receive the message
    $emailTo = '[email protected]';

    // Form fields
    $clientName = addslashes(trim($_POST['name']));
    $clientEmail = addslashes(trim($_POST['email']));
    $number = addslashes(trim($_POST['number']));
    $message = addslashes(trim($_POST['message']));

    // Email Ssubject
    $subject = 'Query from My Domain';

    // Compose message to send
    $sendMessage = 'Hi' . "\n\n";
    $sendMessage .= $message . "\n\n";
    $sendMessage .= 'From: ' . $clientName . "\n";
    $sendMessage .= 'Email: ' . $clientEmail . "\n";
    $sendMessage .= 'Contact number: ' . $number . "\n";

    $array = array();
    $array['nameMessage'] = '';
    $array['emailMessage'] = '';
    $array['numberMessage'] = '';
    $array['messageMessage'] = '';

    if($clientName == '') {
        $array['nameMessage'] = 'Please enter your full name.';
    }
    if (filter_var($clientEmail, FILTER_VALIDATE_EMAIL) == false) {
        $array['emailMessage'] = 'Please insert a valid email address.';
    } 
    if (!preg_match('/^(\+?)+([0-9]{10,})$/', $number)) {
        $array['numberMessage'] = 'Please enter a valid contact number.';
    }
    if($message == '') {
        $array['messageMessage'] = 'Please enter your message.';
    }

    $isValid = empty($array['nameMessage']) && empty($array['emailMessage']) &&
               empty($array['numberMessage']) && empty($array['messageMessage']);   

    if($isValid) {
        // build headers and send mail
        // Headers
        $headers = "From: " . $clientName . ' <' . $clientEmail . '>' . "\r\n";
        $headers .= "CC: " . 'My Boss <[email protected]>' . "\r\n";

        // Send mail
        mail($emailTo, $subject, $sendMessage, $headers);
    }   else {
            //echo the error messages
            echo json_encode($array); 
    }

}   else {
        header ('location: index.html#contact');
    }

?>

scripts.js:

$('.contact-form form').submit(function(e) {
    e.preventDefault();

    var form = $(this);
    var nameLabel = form.find('label[for="contact-name"]');
    var emailLabel = form.find('label[for="contact-email"]');
    var numberLabel = form.find('label[for="contact-number"]');
    var messageLabel = form.find('label[for="contact-message"]');

    nameLabel.html('Full name');
    emailLabel.html('Email');
    numberLabel.html('Contact number');
    messageLabel.html('Message');

    var postdata = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'sendmail.php',
        data: postdata,
        dataType: 'json',
        success: function(json) {
            if(json.nameMessage !== '') {
                nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
            }
            if(json.emailMessage !== '') {
                emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
            }
            if(json.numberMessage !== '') {
                numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
            }
            if(json.messageMessage !== '') {
                messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
            }
        }
    });
});

The form works great and I get emails, all I want to do is add two more behaviors to the form, when you click the submit button a loading gif image must show inside the button and if the email is sent successfully I want to remove the form and replace with a success message. If the form was not for any reason I want the form to say button to revert to it's initial state. How can I go about doing this?

Upvotes: 2

Views: 1733

Answers (4)

Passionate Coder
Passionate Coder

Reputation: 7294

You can easily do this by this

 $('#gif_image').show();
    $.ajax({
          url: uri,
          success: function(){
                 $('#message').html('<div id="alertFadeOut">Record has been added!</div>'); // Diplay message with a fadeout
       $('#alertFadeOut').fadeOut(1000, function () {
                      $('#alertFadeOut').text('');
                  });
    },
          complete: function(){
            $('#gif_image').hide();
          }
        });

    <div id="gif_image"><img src="path/tp/image"></div>
<div id="message"></div>

Upvotes: 0

Rupal Javiya
Rupal Javiya

Reputation: 579

Modify your script.js code as given below:

$('.contact-form form').submit(function(e) {
    e.preventDefault();
    $("#div-id").html('<img src="/images/loading.gif" />');

    var form = $(this);
    var nameLabel = form.find('label[for="contact-name"]');
    var emailLabel = form.find('label[for="contact-email"]');
    var numberLabel = form.find('label[for="contact-number"]');
    var messageLabel = form.find('label[for="contact-message"]');

    nameLabel.html('Full name');
    emailLabel.html('Email');
    numberLabel.html('Contact number');
    messageLabel.html('Message');

    var postdata = form.serialize();

    $.ajax({
        type: 'POST',
        url: 'sendmail.php',
        data: postdata,
        dataType: 'json',
        complete: function(){
          $("#div-id").html('<input type="submit" name="submit" value="submit">');
        },
        success: function(json) {
            if(json.nameMessage !== '') {
                nameLabel.append(' - <span class="red error-label"> ' + json.nameMessage + '</span>');
            }
            if(json.emailMessage !== '') {
                emailLabel.append(' - <span class="red error-label"> ' + json.emailMessage + '</span>');
            }
            if(json.numberMessage !== '') {
                numberLabel.append(' - <span class="red error-label"> ' + json.numberMessage + '</span>');
            }
            if(json.messageMessage !== '') {
                messageLabel.append(' - <span class="red error-label"> ' + json.messageMessage + '</span>');
            }
        }
    });
});

Where div-id will be id of div element inside which your button is set in HTML template.

Just for your knowledge, there are many ways to achieve this with jQuery. below are few ref. link for similar questions

Change submit button to a loading image with jquery

Replace submit button with loading gif

http://www.willmaster.com/library/manage-forms/replacing-submit-button-with-loading-image.php

Upvotes: 1

Whothehellisthat
Whothehellisthat

Reputation: 2152

If you're using a <button> tag for the button, you can set its .innerHTML.

$('.contact-form form').submit(function(e) {
  // ...
  button.innerHTML = "<img src='' />";

  $.ajax({
    // ...
    button.innerHTML = "Click me"; // reset to original content
  });
});

Or you could swap it out with css and display:block;/display:none. There are a number of ways you can actually handle showing and hiding the loading icon, but that should get you started.

Upvotes: 0

Ganesh Putta
Ganesh Putta

Reputation: 2681

function LoadData(){
    $("#loading-image").show();
    $.ajax({
          url: yourURL,
          cache: false,
          success: function(html){
            $("Your div id").append(html);
          },
          complete: function(){
            $("#loading-image").hide();
          }
        });
}
<div id="loading-image"><img src="give your gif umage path"/></div>

Upvotes: 1

Related Questions