【问题标题】:Form Processing Without Leaving Page表单处理不离开页面
【发布时间】:2014-09-05 20:38:30
【问题描述】:

这是我第一次在这个网站上发帖,希望有人能提供帮助。

我有一个时事通讯注册系统。表单调用处理脚本,但在运行时,它会输出到另一个页面。

我希望它在同一页面上处理,并输出适当的消息。

经过一番研究,我能找到的衣柜是这篇文章:similar question

这是我正在使用的代码:

HTML

<h6 class="mailingHeadine">Join Our Mailing List</h6>
    <!-- start newsletter -->
    <form id="mailing_list" name="mailing_list" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" >

        <!-- start maillist -->
        <div class="maillist">
            <input type="text" id="e_mail" name="e_mail" value="Enter Your Email" onfocus="if(this.value=='Enter Your Email')this.value=''; this.className='email'" onblur="if(this.value=='')this.value='Enter Your Email'; this.className='email'" />
            <p class="submit"><button type="submit" name="e_submit" value="Subscribe" id="submit">Join</button></p>

        </div><!-- end maillist -->
    </form><!-- end newsletter -->
    <div id="formResponse" style="display: none;"></div>

页内脚本

<script type="text/javascript">
$("#mailing_list").submit(function() {
$.post('link-to-script.php', {email:    $('e_mail').val(), e_submit: 'yes'}, function(data) {
    $("#formResponse").html(data).fadeIn('100');
    $('#e_mail').val(''); /* Clear the inputs */
}, 'text');
return false;
});
</script>

PHP

<?php include('loader.php'); ?>

<?php include('head.php'); ?>

<?php
if(defined('SMTP') && SMTP == 'true')
{
    include('class.phpmailer.php');
}   
?>

<!-- MAIN -->
<div id="main" class="container-fluid">

    <!-- container content -->
    <div class="container-fluid">

        <!-- row-fluid -->
        <div class="row-fluid">

        <?php if(isset($_POST['e_submit']) && strlen($_POST['e_mail']) !== 0) { ?>

            <?php 

            // The system settings
            include('settings.php');

            // grab the user email
            $email = $_POST['e_mail'];

            // validate the email
            if(substr_count($email,'@') == 1 && substr_count($email,'.') >= 1) 
            {

                // check if user is already subscribed - avoids duplications
                $results = $script->checkSubscription($email);

                // subscribe the user
                if(empty($results))
                {
                    $subscribe_user = $script->subscribeUser($email);

                    // Notify Admin that an user as been subscribed
                    if($subscribe_user)
                    {
                        if($options['script_notifications'] == 'subscriptions' || $options['script_notifications'] == 'both') 
                        {
                            $subject = 'Subscription Notification ID-'.mt_rand(0, 5).': Subscription for: '.$email;

                            $message = str_replace('{EMAIL}', $email, $options['script_notification_message']);
                            $message_send = str_replace('{ACTION}', $translate->__('cancels subscription'), $message);

                            if(defined('SMTP') && SMTP == 'false')
                            {
                                $from = $options['script_email'];
                                $headers = "From: {$from}\r\n";
                                $headers .= "X-Mailer: script\r\n";
                                $headers .= "Content-Type: text/html; charset=utf-8";

                                if($subscribed) 
                                {
                                    @mail($from, $subject, $message_send, $headers);    
                                }

                            } elseif(defined('SMTP') && SMTP == 'true') {

                                $mail = new PHPMailer;

                                $mail->IsSMTP();                                      
                                $mail->Host = SMTP_HOST;  

                                if(defined('SMTP_AUTH') && SMTP_AUTH == 'true')
                                {
                                    $mail->SMTPAuth = true;
                                    $mail->Username = SMTP_USERNAME;                           
                                    $mail->Password = SMTP_PASSWORD;                            
                                } else {
                                    $mail->SMTPAuth = false;    
                                }

                                $mail->From = $options['script_email'];
                                $mail->FromName = 'script';

                                $mail->IsHTML(true);
                                $mail->Subject = $subject;
                                $mail->AddAddress($options['script_email']);
                                $mail->Body = $message_send;

                            }
                        }   
                        echo '          
                            <div class="alert alert-success tac">
                                <img src="images/done.png" width="48" height="48" alt="done"/>
                                <p>Thank you for subscribing to our Newsletter.</p>
                            </div>
                        ';  
                    } else {
                        echo '          
                            <div class="alert alert-error tac">
                                <img src="images/failed.png" width="48" height="48" alt="failed"/>
                                <p>Error occured while subscribing you.</p>
                            </div>
                        ';      
                    }

                } else {
                    echo '          
                        <div class="alert alert-error tac">
                            <img src="images/failed.png" width="48" height="48" alt="failed"/>
                            <p>You are already subscribed to our newsletter.</p>
                        </div>
                    ';      
                }

            } else {
                ?>
                <div class="alert alert-error tac">
                    <img src="images/failed.png" width="48" height="48" alt="failed"/>
                    <p>Invalid E-mail Address</p>
                </div>
                <?php
            }

            ?>

        <?php } else { ?>
            <div class="alert alert-error tac">
                <img src="images/failed.png" width="48" height="48" alt="failed"/>
                <p>You must have an e-mail address in order to subscribe to newsletter</p>
            </div>
        <?php } ?>

        </div><!-- // .row-fluid -->  

    </div>
    <!-- // end content -->

</div>
<!-- // END MAIN -->

</body>
</html>

它只是有点工作。它运行 PHP 脚本并始终输出“您必须有一个电子邮件地址才能订阅时事通讯”,这是 PHP 代码的最后一行。

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript php jquery html


    【解决方案1】:

    一些事情。

    首先,您的 PHP 文件应该只是 PHP -- 没有 HTML。此时,不要尝试将另一个包含 PHP 的 HTML 页面混合为您的 PHP ajax 处理器文件。这很棘手,不推荐。

    我没有对您的 PHP 页面进行故障排除,只是将其简化为应该的样子:

    <?php 
        include('e-includes/loader.php');
        include('e-head.php');
    
        if(defined('SMTP') && SMTP == 'true') {
            include('e-includes/class.phpmailer.php');
        }
    
        if(isset($_POST['e_submit']) && strlen($_POST['e_mail']) !== 0) {
                // The system settings
                include('e-includes/settings.php');
    
                // grab the user email
                $email = $_POST['e_mail'];
    
                // validate the email
                if(substr_count($email,'@') == 1 && substr_count($email,'.') >= 1) {
    
                    // check if user is already subscribed - avoids duplications
                    $results = $easyLetters->checkSubscription($email);
    
                    // subscribe the user
                    if(empty($results)) {
                        $subscribe_user = $easyLetters->subscribeUser($email);
    
                        // Notify Admin that an user as been subscribed
                        if($subscribe_user) {
                            if($options['easyLetters_notifications'] == 'subscriptions' || $options['easyLetters_notifications'] == 'both')  {
                                $subject = 'Subscription Notification ID-'.mt_rand(0, 5).': Subscription for: '.$email;
                                $message = str_replace('{EMAIL}', $email, $options['easyLetters_notification_message']);
                                $message_send = str_replace('{ACTION}', $translate->__('cancels subscription'), $message);
    
                                if(defined('SMTP') && SMTP == 'false') {
                                    $from = $options['easyLetters_email'];
                                    $headers = "From: {$from}\r\n";
                                    $headers .= "X-Mailer: easyLetters\r\n";
                                    $headers .= "Content-Type: text/html; charset=utf-8";
    
                                    if($subscribed) {
                                        @mail($from, $subject, $message_send, $headers);    
                                    }
    
                                } elseif(defined('SMTP') && SMTP == 'true') {
    
                                    $mail = new PHPMailer;
    
                                    $mail->IsSMTP();                                      
                                    $mail->Host = SMTP_HOST;  
    
                                    if(defined('SMTP_AUTH') && SMTP_AUTH == 'true') {
                                        $mail->SMTPAuth = true;
                                        $mail->Username = SMTP_USERNAME;                           
                                        $mail->Password = SMTP_PASSWORD;                            
                                    } else {
                                        $mail->SMTPAuth = false;    
                                    }
    
                                    $mail->From = $options['easyLetters_email'];
                                    $mail->FromName = 'EasyLetters';
    
                                    $mail->IsHTML(true);
                                    $mail->Subject = $subject;
                                    $mail->AddAddress($options['easyLetters_email']);
                                    $mail->Body = $message_send;
    
                                }
                            }
                            echo '          
                                <div class="alert alert-success tac">
                                    <img src="e-images/done.png" width="48" height="48" alt="done"/>
                                    <p>Thank you for subscribing to our Newsletter.</p>
                                </div>
                            ';  
                        } else {
                            echo '          
                                <div class="alert alert-error tac">
                                    <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                                    <p>Error occured while subscribing you.</p>
                                </div>
                            ';      
                        }
    
                    } else {
                        echo '          
                            <div class="alert alert-error tac">
                                <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                                <p>You are already subscribed to our newsletter.</p>
                            </div>
                        ';      
                    }
    
                } else {
                    ?>
                    <div class="alert alert-error tac">
                        <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                        <p>Invalid E-mail Address</p>
                    </div>
                }
    
            } else {
                <div class="alert alert-error tac">
                    <img src="e-images/failed.png" width="48" height="48" alt="failed"/>
                    <p>You must have an e-mail address in order to subscribe to newsletter</p>
                </div>
            }
    

    注意顶部只有一个&lt;?php 标签。这就是你所需要的。剩下的就是 PHP,回显出来的 HTML 作为文本字符串返回。

    现在,如果您在 AJAX 成功函数中没有收到正确的响应,那么您需要对 PHP 程序逻辑进行故障排除。首先将整个 PHP 文件替换为:

    <?php
        die("I am here");
    

    并修改您的 AJAX 代码块以仅显示返回的内容:

        $.post('http://www.american-designer.com/t/News/e-subscribe.php', {email:    $('e_mail').val(), e_submit: 'yes'}, function(data) {
            alert( data );
        }, 'text');
    

    最后,请注意$.post()$.get()$.load() 都是完整 ajax 构造的简写版本:$.ajax()。就个人而言,我发现 $.post 更难使用。

    我建议您阅读更多关于 AJAX 的内容:

    AJAX request callback using jQuery

    【讨论】:

      【解决方案2】:

      我会推荐 Jquery 形式的 Ajax 来处理相同的页面请求。 Ajax 将允许您调用服务器、运行代码并将响应返回到客户端,而无需离开页面甚至重新加载它。您需要首先使用以下方法将库添加到您的页面:

      <script src="http://code.jquery.com/jquery-2.1.1.min.js" ></script>
      

      接下来,您需要确保代码在页面加载之前不会运行。使用:

      $(document).ready(function(){
          //your code will be going here
      });
      

      现在我们使用 jquery 的 onclick() 版本调用 php 页面:

      $(document).ready(function(){
          $("#your_submit_button_id").click(function(){  //when you click the element having that particular id, we execute the function listed.
      
          });
      });    
      

      好的,最后我们必须对php页面进行ajax调用并获得结果。

      $(document).ready(function(){
          $("#your_submit_button_id").click(function(){  //when you click the element having that particular id, we execute the function listed.
              $.ajax({
                  url: "your_file.php",
                  type: "POST",
                  dataType: "xml",  //return type, can be xml, html, or json
                  data: {email: "whatever"}, //this is the data you are sending, you'll have to add some code to get the value of the input. format is: variable_name: "value"
                  success: function(data_returned_from_php){
                     //whatever you decide to echo bakc will be in data_returned_from_php or whatever you decide to call the object
                     //take the data you get back and do whatever the hell you want with it.
                  }
              });
          });
      }); 
      

      页面不会重新加载,但是返回的数据可以附加到页面上,或者你可以 make and alert()

      【讨论】:

        【解决方案3】:

        好的,所以我想办法以防其他人感兴趣。

        <script type="text/javascript">
        $("#mailing_list").submit(function() {
        $.post('link to script here.php', {e_mail:   $('#e_mail').val(), e_submit: 'Subscribe'}, function(data) {
            $("#formResponse").html(data).fadeIn('100');
            $('#e_mail').val(''); /* Clear the inputs */
        }, 'text');
        return false;
        });
        </script>
        

        我遗漏了第二个值“e_submit”、提交按钮的名称以及我需要传递的“值”。

        这个链接帮助了我:PHP Contact Form - Want to stay on my site after send

        感谢所有回复的人。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-24
          • 1970-01-01
          • 2013-04-19
          • 1970-01-01
          • 2014-01-08
          • 1970-01-01
          • 2012-03-02
          相关资源
          最近更新 更多