如何在单击提交按钮时使用加载gif图像替换按钮,然后在成功删除表单上替换,并替换为成功消息

时间:2016-07-21 10:15:03

标签: javascript php jquery html forms

我有一个html表单并使用以下代码来处理它并验证输入字段。

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>');
            }
        }
    });
});

表单效果很好,我收到了电子邮件,我想要做的就是在表单中再添加两个行为,当您单击提交按钮时,加载的gif图像必须显示在按钮内部,如果电子邮件发送成功,我想要删除表单并替换成功消息。如果表单不是出于任何原因,我希望表单说出按钮以恢复其初始状态。我该怎么做呢?

4 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

修改您的script.js代码,如下所示:

$('.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>');
            }
        }
    });
});

其中div-id将是div元素的id,其中您的按钮在HTML模板中设置。

为了您的知识,有很多方法可以通过jQuery实现这一目标。以下几点参考。类似问题的链接

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

答案 2 :(得分:0)

如果您使用按钮的<button>标记,则可以设置其.innerHTML

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

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

或者您可以将其与c​​ss和display:block; / display:none交换出来。有许多方法可以实际处理显示和隐藏加载图标,但这应该可以让你开始。

答案 3 :(得分:0)

您可以通过此

轻松完成此操作
 $('#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>