草庐IT

php - Ajax PHP 联系表单不起作用

coder 2024-05-02 原文

我在使用 php 联系表单时遇到问题。它正在发送空电子邮件,修复后,现在它不发送电子邮件,而是将我重定向到一个空白页面,上面写着“已发送”(在 send-email.php 文件中编码..

本应使用 AJAX 在不离开事件页面的情况下显示成功消息。不知道怎么了。任何帮助表示赞赏。问候, 这是头部部分;

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <style>
.error { display:none; }
.success { display:none; }
</style>

<script type="text/javascript">
    $(document).ready(function(){
        $('#send_message').submit(function(e){
            e.preventDefault();
            var error = false;
            var name = $('#name').val();
            var email = $('#email').val();
            var message = $('#message').val();
            if(name.length == 0){
                var error = true;
                $('#name_error').fadeIn(500);
            } else {
                $('#name_error').fadeOut(500);
            }
            if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email_error').fadeIn(500);
            } else {
                $('#email_error').fadeOut(500);
            }
            if(message.length == 0){
                var error = true;
                $('#message_error').fadeIn(500);
            } else {
                $('#message_error').fadeOut(500);
            } if(error == false){
                $('#cf_submit_p').attr({'disabled' : 'true', 'value' : 'Gönderiliyor...' });
                $.post("send_email.php", $("#contact_form").serialize(),function(result){
                    if(result == 'sent'){
                        $('#cf_submit_p').remove();
                        $('#mail_success').fadeIn(500);
                    } else {
                        $('#mail_fail').fadeIn(500);
                        $('#cf_submit_p').removeAttr('disabled').attr('value', 'Gönder');
                    }
                });
            }
        });
    });
</script>

这是正文部分;

<div class="container-fluid">
                        <p id="returnmessage"></p>
                        <form action="send_email.php" id="contact_form" method="post">
                            <h2 style="font-size:14px;line-height:18px;font-weight:600;padding-bottom:0;">Bize Yazın</h2>
                            <ul class="contactform">
                                <li>
                                    <div id="name_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Lütfen adınızı giriniz.</div>
                                    <span class="contact-input-icon" style="text-align:left"><i class="fa fa-user"></i></span>
                                    <div class="input-field">
                                        <input type="text" style="border:1px solid rgba(220,220,220,0.5)" name="name" id="name" value="" class="required requiredField" placeholder="Ad Soyad"/>
                                    </div>
                                </li>
                                <li>
                                    <div id="email_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Lütfen eposta adresinizi giriniz.</div>
                                    <span class="contact-input-icon"><i class="fa fa-envelope"></i></span>
                                    <div class="input-field">
                                        <input type="email" style="border:1px solid rgba(220,220,220,0.5)" name="email" id="email" value="" class="required requiredField email" placeholder="Eposta"/>
                                    </div>
                                </li>
                                <li class="textarea">
                                    <div id="message_error" class="error" style="color:#aa3939; font-size:8px; line-height:8px;"> <i class="fa fa-exclamation"></i> Lütfen mesajınızı giriniz.</div>
                                    <span class="contact-input-icon"><i class="fa fa-pencil"></i></span>
                                    <div class="input-field">
                                        <textarea name="message" style="border:1px solid rgba(220,220,220,0.5)" id="message" rows="6" cols="20" class="required requiredField" placeholder="Mesajınız"></textarea>
                                    </div>
                                    <div id="mail_success" class="success" style="color:#00CC00"><i class="fa fa-check"></i> İlginiz için teşekkürler. En kısa sürede sizinle irtibata geçeceğiz.</div>
                                    <div id="mail_fail" class="error" style="color:#aa3939"><i class="fa fa-times"></i> Üzgünüz, mesajınız iletilemedi. Daha sonra lütfen tekrar deneyin.</div>
                                </li>
                                <li class="buttons">
                                    <div id="cf_submit_p">
                                    <input type="hidden" style="border:1px solid rgba(220,220,220,0.5)" name="submitted" id="submitted" value="true" />
                                    <button type="submit" style="border:1px solid #3f97cf" class="button" id="send_message"><i class="fa fa-paper-plane-o" style="font-size:20px;color:#3f97cf"></i></button>
                                    </div>
                                </li>
                            </ul>
                        </form>
                    </div> <!--end container-fluid-->

这里是 send_email.php;

<?php

    $autoResponse = true; //if set to true auto response email will be sent, if you don't want autoresponse set it to false
    $autoResponseSubject = "İletişim Formu"; 
    $autoResponseMessage = "<html>
    <head>
        <title>This is your HTML email!</title>
    </head>
    <body> 
        <div style='width:700px; font-family:Arial, Helvetica, sans-serif; font-size:44px; color:#CCC; text-align:center; margin:0 auto; padding:20px;'>THIS IS YOUR</div>/>
    </body>
    </html>";
    $autoResponseHeaders = "Kimden: yeterkara90@gmail.com";
    $autoResponseHeaders .= "MIME-Version: 1.0"."\r\n";
    $autoResponseHeaders .= "Content-type: text/html; charset=iso-8859-1"."\r\n";  

    //we need to get our variables first
    $to =   'yeterkara90@gmail.com'; //the address to which the email will be sent
    $name     =   $_POST['name'];
    $email    =   $_POST['email'];
    $subject  =   "Site İletişim Formu";
    $msg  =   $_POST['message'];

    $message = "Kimden: $name "."\r\n"."Eposta: $to "."\r\n";

    /*the $header variable is for the additional headers in the mail function,
     we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
     That way when we want to reply the email gmail(or yahoo or hotmail...) will know
     who are we replying to. */
    $headers  = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";


    if(mail($to, $subject, $message, $headers)){
        if($autoResponse === true){
            mail($email, $autoResponseSubject, $autoResponseMessage, $autoResponseHeaders);
        }
        echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
    }else{
        echo 'failed';// ... or this one to tell it that it wasn't sent
    }


?>

最佳答案

对于不提交的表单,您应该向 jQuery 中的提交函数返回 false。它不是重定向,而是提交给 send_email.php。添加return false后的jquery代码。

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
    <style>
.error { display:none; }
.success { display:none; }
</style>

<script type="text/javascript">
    $(document).ready(function(){
        $('#send_message').submit(function(e){
            e.preventDefault();
            var error = false;
            var name = $('#name').val();
            var email = $('#email').val();
            var message = $('#message').val();
            if(name.length == 0){
                var error = true;
                $('#name_error').fadeIn(500);
            } else {
                $('#name_error').fadeOut(500);
            }
            if(email.length == 0 || email.indexOf('@') == '-1'){
                var error = true;
                $('#email_error').fadeIn(500);
            } else {
                $('#email_error').fadeOut(500);
            }
            if(message.length == 0){
                var error = true;
                $('#message_error').fadeIn(500);
            } else {
                $('#message_error').fadeOut(500);
            } if(error == false){
                $('#cf_submit_p').attr({'disabled' : 'true', 'value' : 'Gönderiliyor...' });
                $.post("send_email.php", $("#contact_form").serialize(),function(result){
                    if(result == 'sent'){
                        $('#cf_submit_p').remove();
                        $('#mail_success').fadeIn(500);
                    } else {
                        $('#mail_fail').fadeIn(500);
                        $('#cf_submit_p').removeAttr('disabled').attr('value', 'Gönder');
                    }
                });
            }
            return false;
        });
    });
</script>

在您的 PHP 代码中,您应该在向您发送电子邮件之前检查数据是否已发布。像这样

<?php

    $autoResponse = true; //if set to true auto response email will be sent, if you don't want autoresponse set it to false
    $autoResponseSubject = "İletişim Formu"; 
    $autoResponseMessage = "<html>
    <head>
        <title>This is your HTML email!</title>
    </head>
    <body> 
        <div style='width:700px; font-family:Arial, Helvetica, sans-serif; font-size:44px; color:#CCC; text-align:center; margin:0 auto; padding:20px;'>THIS IS YOUR</div>/>
    </body>
    </html>";
    $autoResponseHeaders = "Kimden: yeterkara90@gmail.com";
    $autoResponseHeaders .= "MIME-Version: 1.0"."\r\n";
    $autoResponseHeaders .= "Content-type: text/html; charset=iso-8859-1"."\r\n";  

    //we need to get our variables first
    $to =   'yeterkara90@gmail.com'; //the address to which the email will be sent
    $name     =   $_POST['name'];
    $email    =   $_POST['email'];
    $subject  =   "Site İletişim Formu";
    $msg  =   $_POST['message'];

    $message = "Kimden: $name "."\r\n"."Eposta: $to "."\r\n";

    /*the $header variable is for the additional headers in the mail function,
     we are asigning 2 values, first one is FROM and the second one is REPLY-TO.
     That way when we want to reply the email gmail(or yahoo or hotmail...) will know
     who are we replying to. */
    $headers  = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";

    if( $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['email']) ){
        if(mail($to, $subject, $message, $headers)){
            if($autoResponse === true){
                mail($email, $autoResponseSubject, $autoResponseMessage, $autoResponseHeaders);
            }
            echo 'sent'; // we are sending this text to the ajax request telling it that the mail is sent..
        }else{
            echo 'failed';// ... or this one to tell it that it wasn't sent
        }
    }


?>

关于php - Ajax PHP 联系表单不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30979171/

有关php - Ajax PHP 联系表单不起作用的更多相关文章

  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-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中的所有其他对象

  3. 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

  4. 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

  5. ruby - 字符串文字前面的 * 在 ruby​​ 中有什么作用? - 2

    这段代码似乎创建了一个范围从a到z的数组,但我不明白*的作用。有人可以解释一下吗?[*"a".."z"] 最佳答案 它叫做splatoperator.SplattinganLvalueAmaximumofonelvaluemaybesplattedinwhichcaseitisassignedanArrayconsistingoftheremainingrvaluesthatlackcorrespondinglvalues.Iftherightmostlvalueissplattedthenitconsumesallrvaluesw

  6. ruby - 为什么这个 eval 在 Ruby 中不起作用 - 2

    你能解释一下吗?我想评估来自两个不同来源的值和计算。一个消息来源为我提供了以下信息(以编程方式):'a=2'第二个来源给了我这个表达式来评估:'a+3'这个有效:a=2eval'a+3'这也有效:eval'a=2;a+3'但我真正需要的是这个,但它不起作用:eval'a=2'eval'a+3'我想了解其中的区别,以及如何使最后一个选项起作用。感谢您的帮助。 最佳答案 您可以创建一个Binding,并将相同的绑定(bind)与每个eval相关联调用:1.9.3p194:008>b=binding=>#1.9.3p194:009>eva

  7. ruby-on-rails - 从 ActiveAdmin has_many 表单助手中删除 "Add new"按钮 - 2

    我在事件管理员编辑页面中有嵌套资源,但我只想允许管理员编辑现有资源的内容,而不是添加新的嵌套资源。我的代码看起来像这样:formdo|f|f.inputsdof.input:authorf.input:contentf.has_many:commentsdo|comment_form|comment_form.input:contentcomment_form.input:_destroy,as::boolean,required:false,label:'Remove'endendf.actionsend但它在输入下添加了“添加新评论”按钮。我怎样才能禁用它,并只为主窗体保留f.ac

  8. ruby-on-rails - Spring 不起作用。 [未初始化常量 Spring::SID::DL] - 2

    我无法运行Spring。这是错误日志。myid-no-MacBook-Pro:myid$spring/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/lib/spring/sid.rb:17:in`fiddle_func':uninitializedconstantSpring::SID::DL(NameError)from/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/li

  9. ruby-on-rails - 用于 Rails 的 HAML 表单 - 2

    我目前正在尝试将ERB布局转换为HAML。这是我不断收到的错误:index.html.haml:18:syntaxerror,unexpected')'));}\n#{_hamlout.format_...这是HAML页面:.row-fluid.span6%h2TodoList.span6%h2{:style=>"text-align:right;"}document.write(today)%hr.divider.row-fluid.span6%h2.small_headNewTask=render:partial=>'layouts/form_errors',:locals=>{:

  10. ruby-on-rails - 如何在 Rails 中为现有模型生成表单? - 2

    为现有模型生成单个文件(_form.html.erb)的命令是什么?在Rails3中工作。谢谢。 最佳答案 这听起来可能很傻,但请听我说完……当我想开始清洁时,我自己也做过几次这样的事情。以下是一个脚本,它将读取您的模式并生成必要的生成命令来重现它:require'rubygems'require'active_support/core_ext'schema=File.read('db/schema.rb')schema.scan(/create_table"(\w+)",.*?\n(.*?)\nend/m).eachdo|name

随机推荐