草庐IT

php - 弹出表单ajax请求不起作用

coder 2024-04-25 原文

我想在我的站点中添加弹出式联系表单,我从互联网上举了一个例子,并对其发送邮件进行了一些更改,并将其用于将数据插入数据库。所以这是我的第一个文件 index.php

<!doctype html>
<html lang="en">
<head>

    <title>A Slick Ajax Contact Form with jQuery and PHP</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

    <script type="text/javascript">

        var messageDelay = 2000; // How long to display status messages (in milliseconds)

        // Init the form once the document is ready
        $(init);

        // Initialize the form
        function init() {

            // Hide the form initially.
            // Make submitForm() the form's submit handler.
            // Position the form so it sits in the centre of the browser window.
            $('#contactForm').hide().submit(submitForm).addClass('positioned');

            // When the "Send us an email" link is clicked:
            // 1. Fade the content out
            // 2. Display the form
            // 3. Move focus to the first field
            // 4. Prevent the link being followed

            $('a[href="#contactForm"]').click(function() {
                $('#content').fadeTo('slow', .2);
                $('#contactForm').fadeIn('slow', function() {
                    $('#senderName').focus();
                })

                return false;
            });

            // When the "Cancel" button is clicked, close the form
            $('#cancel').click(function() {
                $('#contactForm').fadeOut();
                $('#content').fadeTo('slow', 1);
            });

            // When the "Escape" key is pressed, close the form
            $('#contactForm').keydown(function(event) {
                if (event.which == 27) {
                    $('#contactForm').fadeOut();
                    $('#content').fadeTo('slow', 1);
                }
            });

        }

        // Submit the form via Ajax
        function submitForm() {

            var contactForm = $(this);

            // Are all the fields filled in?
            if (!$('#senderName').val() || !$('#senderEmail').val() || !$('#ContactNo').val() || !$('#message').val()) {

                // No; display a warning message and return to the form
                $('#incompleteMessage').fadeIn().delay(messageDelay).fadeOut();
                contactForm.fadeOut().delay(messageDelay).fadeIn();

            } else {

                // Yes; submit the form to the PHP script via Ajax
                $('#sendingMessage').fadeIn();
                contactForm.fadeOut();

                $.ajax({
                    url: contactForm.attr('action') + "?ajax=true",
                    type: contactForm.attr('method'),
                    data: contactForm.serialize(),
                    success: submitFinished
                });

            }

            // Prevent the default form submission occurring
            return false;
        }

        // Handle the Ajax response
        function submitFinished(response) {
            response = $.trim(response);
            $('#sendingMessage').fadeOut();

            if (response == "success") {

                // Form submitted successfully:
                // 1. Display the success message
                // 2. Clear the form fields
                // 3. Fade the content back in

                $('#successMessage').fadeIn().delay(messageDelay).fadeOut();
                $('#senderName').val("");
                $('#senderEmail').val("");
                $('#ContactNo').val("");
                $('#message').val("");

                $('#content').delay(messageDelay + 500).fadeTo('slow', 1);

            } else {

                // Form submission failed: Display the failure message,
                // then redisplay the form
                $('#failureMessage').fadeIn().delay(messageDelay).fadeOut();
                $('#contactForm').delay(messageDelay + 500).fadeIn();

            }

        }

    </script>

</head>
<body>

    <div id="content">
        <p style="padding-bottom: 50px; font-weight: bold; text-align: center;"><a href="#contactForm">~ Send us an email ~</a></p>
    </div>

    <form id="contactForm" action="processForm.php" method="post">
        <h2>Send us an email...</h2>
        <ul>
            <li>
                <label for="senderName">Full Name</label>
                <input type="text" name="senderName" id="senderName" placeholder="Please type your name" required="required" maxlength="40" />
            </li>
            <li>
                <label for="senderEmail">Email</label>
                <input type="email" name="senderEmail" id="senderEmail" placeholder="Please type your email address" required="required" maxlength="50" />
            </li>
            <li>
                <label for="ContactNo">Contact No</label>
                <input type="text" name="ContactNo" id="ContactNo" placeholder="Please type your contact no" required="required" maxlength="50" />
            </li>
            <li>
                <label for="message" style="padding-top: .5em;">Your Message</label>
                <textarea name="message" id="message" placeholder="Please type your message" required="required" cols="80" rows="10" maxlength="10000"></textarea>
            </li>
        </ul>
        <div id="formButtons">
            <input type="submit" id="sendMessage" name="sendMessage" value="Send Email" />
            <input type="button" id="cancel" name="cancel" value="Cancel" />
        </div>
    </form>

    <div id="sendingMessage" class="statusMessage">
        <p>Sending your message. Please wait...</p>
    </div>

    <div id="successMessage" class="statusMessage">
        <p>Thanks for sending your message! We'll get back to you shortly.</p>
    </div>

    <div id="failureMessage" class="statusMessage">
        <p>There was a problem sending your message. Please try again.</p>
    </div>

    <div id="incompleteMessage" class="statusMessage">
        <p>Please complete all the fields in the form before sending.</p>
    </div>

</body>
</html>

还有一个是processForm.php。

<?php

// Read the form values
$success     = false;
$senderName  = isset( $_POST['senderName'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['senderName'] ) : "";
$senderEmail = isset( $_POST['senderEmail'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail'] ) : "";
$ContactNo   = isset( $_POST['ContactNo'] ) ? preg_replace( "/[^\ 0-9]/", "", $_POST['ContactNo'] ) : "";
$message     = $_POST['message'];

// If all values exist, send the email
if ( $senderName && $senderEmail && $contactNo && $message ) {

    include("config.php");
    $success = mysql_query("INSERT INTO `inquiry` (`name`, `contact`, `email`, `query`) VALUES ('$senderName', '$ContactNo', '$senderEmail', '$message')");

}

// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {

    echo $success ? "success" : "error";

} else { ?>

    <html>
    <head>
        <title>Thanks!</title>
    </head>
    <body>

        <?php if ( $success ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
        <?php if ( !$success ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
        <p>Click your browser's Back button to return to the page.</p>

    </body>
    </html>

<?php } ?>

问题是当我提交正确时显示消息“发送您的消息时出现问题。请重试。”请帮助我。

最佳答案

我认为你应该改变这一行。

if ( $senderName && $senderEmail && $contactNo && $message ) {

if ( $senderName && $senderEmail && $ContactNo && $message ) {

关于php - 弹出表单ajax请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33318817/

有关php - 弹出表单ajax请求不起作用的更多相关文章

  1. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  2. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  5. ruby - 如何在 Rails 4 中使用表单对象之前的验证回调? - 2

    我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser

  6. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  7. jquery - 如何将 AJAX 变量从 jQuery 传递到他们的 Controller ? - 2

    我有一个电子邮件表格。但是我正在制作一个测试电子邮件表单,用户可以在其中添加一个唯一的电子邮件,并让电子邮件测试将其发送到该特定电子邮件。为了简单起见,我决定让测试电子邮件通过ajax执行,并将整个内容粘贴到另一个电子邮件表单中。我不知道如何将变量从我的HAML发送到我的Controllernew.html.haml-form_tagadmin_email_blast_pathdoSubject%br=text_field_tag'subject',:class=>"mass_email_subject"%brBody%br=text_area_tag'message','',:nam

  8. ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用? - 2

    我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o

  9. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  10. ruby - HTTP 请求中的用户代理,Ruby - 2

    我是Ruby的新手。我试过查看在线文档,但没有找到任何有效的方法。我想在以下HTTP请求botget_response()和get()中包含一个用户代理。有人可以指出我正确的方向吗?#PreliminarycheckthatProggitisupcheck=Net::HTTP.get_response(URI.parse(proggit_url))ifcheck.code!="200"puts"ErrorcontactingProggit"returnend#Attempttogetthejsonresponse=Net::HTTP.get(URI.parse(proggit_url)

随机推荐