如何在联系表格中使用ajax

时间:2016-05-30 18:00:50

标签: php jquery ajax

我有一个简单的联系表单,对其进行了一些验证。我已经在谷歌搜索了几个小时,发现了很多关于如何创建联系人的东西可以做各种各样的事情,但我只是在寻找一些非常简单的东西。我希望使用我的表单,因为我希望添加一些ajax代码以使页面不像现在那样重新加载,并在表单提交时显示一个小动画gif替换提交按钮,然后显示我有成功的消息。

<?php
// define variables and set to empty values
$error = ""; $successMessage = "";
$fname = $email = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $error .= "First name is required.<br>";
  } else {
    $fname = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
      $error .= "Only letters and white space allowed.<br>"; 
    }
  }

  if (empty($_POST["email"])) {
    $error .= "Email is required.<br>";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $error .= "Invalid email format.<br>"; 
    }
  }


  if (empty($_POST["message"])) {
      $error .= "Message is required.<br>";
  } else {
    $message = test_input($_POST["message"]);
  }

    if ($error != "") {

            $error = '<div class="formerror" role="alert"><p><strong>There were error(s) in your form:</strong><br></p>' . $error . '</div>';
 } else {

     $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';

           // $emailTo = "me@mydomain.com";

            //$subject = $_POST['subject'];

            //$content = $_POST['content'];

        //    $headers = "From: ".$_POST['email'];

        //    if (mail($emailTo, $subject, $content, $headers)) {

          //      $successMessage = '<div class="alert alert-success" role="alert">Your message was sent, we\'ll get back to you ASAP!</div>';


        //    } else {

        //        $error = '<div class="alert alert-danger" role="alert"><p><strong>Your message couldn\'t be sent - please try again later</div>';

            }
 //}

}



function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


?>

表格代码:

 <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="cform">
    <input type="text" class="contactfield cformbottom" id="name" placeholder="Your full name" name="name" value="<?php echo $fname;?>">

    <input type="email" class="contactfield cformbottom" id="email" name="email" placeholder="Your email" value="<?php echo $email;?>">


    <textarea class="contactfield" id="message" name="message" rows="3" placeholder="Your Message" value="<?php echo $message;?>"></textarea>
          </div>
  <input type="submit" class="newsbut" value="Submit">
</form><br>
         <div id="error"><? echo $error.$successMessage; ?></div>

jQuery验证:

 <script type="text/javascript">

          $("form").submit(function(e) {

              var error = "";

              if ($("#name").val() == "") {

                  error += "Your name is required.<br>"

              }

              if ($("#email").val() == "") {

                  error += "Your email is required.<br>"

              }

              if ($("#message").val() == "") {

                  error += "Your message is required.<br>"

              }

              if (error != "") {

                 $("#error").html('<div class="formerror" role="alert"><p><strong>There were error(s) in your form:</strong></p>' + error + '</div>');

                  return false;

              } else {

                  return true;

              }
          })


    </script>

1 个答案:

答案 0 :(得分:0)

您可以使用我在下面发布的方法。只需阅读函数上方的注释,并使用适当的参数调用该函数。 在调用remote_call之前,您可以调用另一个方法load_image,并在回调中的响应之后调用deload_image函数。

这是发送ajax请求的旧方法。 apis将很快删除,只需要创建浏览器对象功能(下面的最后一个方法将被修改)。

另请注意,在下面的方法中,调用自定义Alert函数来修改警报函数的行为     // ================================================ ============================================ //     // =========================================发送AJAX请求==== ============================ //     // ================================================ ============================================ //     / *     强制对象。它应该具有如下所述的各种属性。有些是疯子和其他可选的     强制object.actionScriptURL =要调用的页面的相对路径(相对于服务器的doc根)                             它也可以是urlwith查询字符串     可选的object.sendMethod = POST / GET。默认值为post     可选的object.callType = ASYNC / SYNC。默认值为ASYNC     可选的object.additionalData =要像formdata一样发送的AnyData     可选object.callBack =从服务器回调wid响应的任何函数。如果传递函数作为对象,那么该函数必须具有参数配置     * /

function send_remoteCall(object)
{
    var callType = true, sendMethod =   'POST', additionalData  =   null, callBack  =   '';
    if(IsValueNull(object.actionScriptURL))
        return false;

    if(IsValueNull(object.sendMethod))
        sendMethod  =   'POST';

    if(!IsValueNull(object.callType) && object.callType ==  'SYNC') 
        callType    =   false;

    additionalData  =   object.additionalData;

    var xmlHttp =   createBrowserObject();
    if(!IsValueNull(object.callBack) )
    {
        callBack    =   object.callBack; 
        xmlHttp.onreadystatechange  =   function(){
            if(xmlHttp.readyState   ==  4 && xmlHttp.status ==  200)
            callBack(xmlHttp.responseText);
        }; 
    }
    xmlHttp.open(sendMethod,object.actionScriptURL,callType);
    if(additionalData != null && additionalData != undefined ){
        xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlHttp.setRequestHeader("Content-length", additionalData.length);
        xmlHttp.setRequestHeader("Connection", "close");
    }
    xmlHttp.send(additionalData); 
}

function loadImage()
{
    //document.getElementById('LayOutDiv').style.display = "block";
    //showCenter('<div id="fade"><img src="../../Common/images/aloader.gif"></div>');
    //document.getElementById('LayOutDiv').innerHTML = '<img src="../../Common/images/aloader.gif">'; 
    var LoadingImage    =   document.getElementById('LoadingImage');
    if(!IsValueNull(LoadingImage)){
        LoadingImage.style.display = "block";
        showCenter('LoadingImage');
    }
    LayOutDiv   =   document.getElementById('LayOutDiv');
    if(!IsValueNull(LayOutDiv))
        LayOutDiv.style.display = "block";
    setTimeout(deloadImage, 15000);
}

/*=======================================================*/
//===========FUNCTION TO HIDE THE LOADING EFFECT==========
/*======================================================*/

function deloadImage()
{
    //document.getElementById('LayOutDiv').innerHTML = ''; 
    LoadingImage= document.getElementById('LoadingImage');
    if(!IsValueNull(LoadingImage))
        LoadingImage.style.display = "none";
    LayOutDiv   =   document.getElementById('LayOutDiv');
    if(!IsValueNull(LayOutDiv))
        LayOutDiv.style.display = "none";
}


//==============================================================================================//
//========================= CREATE BROWSE OBJECT FOR AJAX =======================//
//==============================================================================================//
function createBrowserObject()
{
    if(xmlHttp)
        delete xmlHttp;

    var xmlHttp;
    try
    {
        xmlHttp=new XMLHttpRequest();   // Firefox, Opera 8.0+, Safari      
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer                   
        } 
        catch (e)
        { 
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            { 
                Alert(JavascriptNotWorking); 
            }
        }
    }

    return xmlHttp;
}