简体   繁体   English

.ajax和.click不想在简单的联系表格上为我工作

[英].ajax and .click don't want to work for me on a simple contact form

I am in the process of stripping out some html/css from a webstie that was built badly with a framework. 我正在从一个框架中严重构建的webstie中剥离出一些html / css。 This contact form works on the site that uses the framework but when I cut and paste it into its' own set of files, I get no response when I click the submit button. 此联系表单适用于使用框架的站点,但当我将其剪切并粘贴到其自己的文件集中时,单击提交按钮时,我得不到任何响应。 The file has several includes for a header, footer and right side contact form. 该文件包含多个包含页眉,页脚和右侧联系表单的内容。 The header.php file has a lot of unrelated code and the important links to several JS and CSS libraries: header.php文件有很多不相关的代码和几个JS和CSS库的重要链接:

<link href="/media/css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="/media/css/stylesheet.css" rel="stylesheet" type="text/css" />
<link href="/media/css/responsive.css" rel="stylesheet" type="text/css" />
<link href="/media/css/font-awesome.css" rel="stylesheet" type="text/css" />
<script src="/media/js/jquery-latest.min.js" type="text/javascript" ></script>
<script src="/media/js/bootstrap.js" type="text/javascript"></script>
<script src="/media/js/jquery.anchor.js" type="text/javascript"></script>
<script src="/media/js/bootstrap-select.js" type="text/javascript"></script>
<!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

The main content section of the page has some static content and the include for the contact form. 页面的主要内容部分包含一些静态内容和联系表单的包含。 The contact form is: 联系表格是:

    <div class="right-section col-md-3 col-sm-3">
    <div class="row">
    <div class="Login-form">
    <div class="login-top"><h1>Drop Us A Message</h1></div>
    <div class="login-body">
     <div class="successHolder topMargin whiteText" id="basicsSuccess">
              Thank you. Your message has been sent. We will get back to you shortly.
     </div>
     <div class="errorsHolder" id="contactFormErrors">
            Please correct the following errors;

            <ul>
                <span id="nameErrorShow" style="display:none;"><li><span id="nameError"></span></li></span>
                <span id="emailErrorShow" style="display:none;"><li><span id="emailError"></span></li></span>
                <span id="phoneErrorShow" style="display:none;"><li><span id="phoneError"></span></li></span>
                <span id="messageErrorShow" style="display:none;"><li><span id="messageError"></span></li></span>
            </ul>
        </div>
    <div class="">
    <form method="POST" name="contactUsForm" id="contactUsForm">
            <label for="name">Name:</label>
            <input type="text" id="name" name="name" />
            <label for="email">Email:</label>
            <input type="text" id="email" name="email" />
            <label for="phone">Phone:</label>
            <input type="text" id="phone" name="phone" />
            <label for="message">Comments:</label>
            <textarea  id="comments" name="comments"></textarea>
            <button type="submit" name="submitContactForm" id="submitContactForm" value="true" class="btn bt">Submit</button>
            <input type="hidden" name="currentpage" id="currentpage" value="<?=isset($currentpage)?$currentpage:"no page set";?>">
    </form>
    </div>
    </div>
    </div>
    </div> <!--right-section-->
<style type="text/css">
    textarea{
        background: none repeat scroll 0 0 #ecede9;
        border: 1px solid #c9cac6;
        height: 118px;
        padding: 0 2%;
        width: 85%;
        margin-left: 24px;
    }
</style>    

Javascript: 使用Javascript:

<script type="text/javascript">
    function hideContactErrors() {
        document.getElementById("contactFormErrors").style.display = "none";
        document.getElementById("nameErrorShow").style.display = "none";
        document.getElementById("emailErrorShow").style.display = "none";
        document.getElementById("phoneErrorShow").style.display = "none";
        document.getElementById("messageErrorShow").style.display = "none";
    }

    $("#submitContactForm").click(
        function() {
            hideContactErrors();

            var data = {
                "name":$("#name").val(),
                "email":$("#email").val(),
                "phone":$("#phone").val(),
                "comments":$("#comments").val(),
                "currentpage" : $("#currentpage").val()
            };

            data = $(this).serialize() + "&" + $.param(data);

            $.ajax({
                type: "POST",
                dataType: "json",
                url: mailer.php,
                data: data,
                success: function(data) { 
                    if(data["status"] == "success") {
                        $(".successHolder").show();
                        setTimeout(function(){
                        $(".successHolder").hide();
                        },2000)
                        $("#name").val("")
                        $("#email").val("")
                        $("#phone").val("")
                        $("#comments").val("")
                        $("#subject").val("")
                    } else {
                        document.getElementById("contactFormErrors").style.display = "block";

                        /*
                         ********************************
                         * Test each error and display if needed
                         */
                        if(data["name"] != undefined) {
                            document.getElementById("nameErrorShow").style.display = "inline";
                            document.getElementById("nameError").innerHTML = data["name"];
                        }
                        if(data["email"] != undefined) {
                            document.getElementById("emailErrorShow").style.display = "inline";
                            document.getElementById("emailError").innerHTML = data["email"];
                        }
                        if(data["phone"] != undefined) {
                            document.getElementById("phoneErrorShow").style.display = "inline";
                            document.getElementById("phoneError").innerHTML = data["phone"];
                        }
                        if(data["comments"] != undefined) {
                            document.getElementById("messageErrorShow").style.display = "inline";
                            document.getElementById("messageError").innerHTML = data["comments"];
                        }
                    }
                }
            });
            return false;
        }
    );
</script>

The php mailer script: php邮件脚本:

<?php 

if(!isset($hasError)) {
        $emailTo = 'xyz@abc.com'; // Put your own email address here
        $body = "Name: $name \n\nEmail: $email \n\nPhone Number: $phone \n\nSubject: $subject \n\nComments:\n $comments \n\nCurrent page: $currentpage";
        $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

        mail($emailTo, $subject, $body, $headers);
        $emailSent = true;
    }
}
?>  

The original contact form works - the only difference I have made is to replace the URL that was "/ajax/website/contact/process", with "mailer.php". 原始联系表单有效 - 我唯一的区别是用“mailer.php”替换“/ ajax / website / contact / process”的URL。 I have tried using the the debug console in chrome and it gives me different errors depending on when I try it. 我尝试在chrome中使用调试控制台,它根据我尝试的时间给出了不同的错误。 It sometimes says the "$("#submitContactForm").click( " is an unrecognized function. 它有时会说“$(”#submitContactForm“)。click(”是一个无法识别的函数。

As best I can figure out the submitContactForm matches the button id but I'm unsure if it is looking for something buried deeper in the stack that was included with the phpixie framework that I no longer want to use. 最好的我可以弄清楚submitContactForm匹配按钮ID,但我不确定它是否正在寻找埋藏在我不再想使用的phpixie框架中包含的堆栈中更深层次的东西。

I have looked at many examples of contact form code and it seems fairly straight forward - I have gotten several other examples to work fine. 我已经查看了许多联系表单代码的例子,看起来相当简单 - 我还有其他几个例子可以正常工作。 I need to make this work pretty much as written instead of starting over. 我需要完成这项工作,而不是重新开始。 Figuring this out will help to make similar forms work without the underlying framework. 弄清楚这将有助于使类似的表单在没有底层框架的情况下工作。

I am trying to keep this simple while reusing as much of the code as possible. 我试图保持这个简单,同时尽可能多地重用代码。 There are several other forms that I need to work on and I would like to figure out the best way of stripping out whatever framework stuff is burried in the code. 我需要处理其他几种形式,我想找出剥离代码中埋藏的任何框架内容的最佳方法。

  • You're adding the data twice 您要添加两次数据
  • Style tags outside the <head> <head>外的样式标签
  • URL in $.ajax not quoted, ends up being an undefined variable $ .ajax中没有引用的URL,最终是一个未定义的变量
  • Invalid HTML,spans and LI's in a strange mix 无效的HTML,跨度和LI在一个奇怪的混合中

Here's what it should look like 这是它应该是什么样子

function hideContactErrors() {
    $('#contactFormErrors, #nameErrorShow, #emailErrorShow, #phoneErrorShow, #messageErrorShow').hide();
}

$('#contactUsForm').on('submit', function(e) {
    e.preventDefault();
    hideContactErrors();

    $.ajax({
        url      : 'mailer.php',
        type     : 'POST',
        dataType : 'json',
        data     : $(this).serialize()
    }).done(function(data) {
        if (data.status == "success") {
            $(".successHolder").show().delay(2000).hide(1);
            $("#name, #email, #phone, #comments, #subject").val("")
        } else {
            $("#contactFormErrors").hide();
            $("#nameErrorShow").show().find('span').html(function(_, html) {return data.name||html;});
            $("#emailErrorShow").show().find('span').html(function(_, html) {return data.email||html;});
            $("#phoneErrorShow").show().find('span').html(function(_, html) {return phone.name||html;});
            $("#messageErrorShow").show().find('span').html(function(_, html) {return comments.name||html;});
        }
    });
});

try this, 试试这个,

move the jquery click event to jQuery onready, 将jquery click事件移动到jQuery onready,

   $(document).ready(function(){
        $("#submitContactForm").click(
            function() {
               // Your code here
            }
        );
   });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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