2

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 = 'example@gmail.com';

    // 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 <boss@gmail.co.za>' . "\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?

Innocent Monareng
  • 129
  • 1
  • 2
  • 12

4 Answers4

1

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>
Ganesh Putta
  • 2,622
  • 2
  • 19
  • 26
1

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

Community
  • 1
  • 1
Rupal Javiya
  • 591
  • 5
  • 14
  • Thanks the button does behave how I want it. But how to I make it such that on success (only when the email is sent) the entire form disappear and the message "Thanks for contacting us, we will get back to you soon" display? – Innocent Monareng Jul 21 '16 at 11:33
  • Ok, then you need to write code in "success" where same like checking json.numberMessage you can send some boolean value from your php script which is set to true on email successfully sent. afterwards you may use if condition and can replace your page content. check here https://jsfiddle.net/spu7zaae/ hows your form and js code looks like – Rupal Javiya Jul 21 '16 at 12:17
  • I get the emails but the form does not fade and not message appears. The error seems to be working fine though. – Innocent Monareng Jul 21 '16 at 14:59
  • Are you return json.emailSent variable from your php file after sending an email? you should have return json_encode('json'=>array('emailSent' => true)) in your php file last line, and then you may alert it in javascript, if you get this variable value then everything will works correctly – Rupal Javiya Jul 22 '16 at 12:21
0

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.

Whothehellisthat
  • 2,072
  • 1
  • 14
  • 14
0

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>
Passionate Coder
  • 7,154
  • 2
  • 19
  • 44