表格处理不离开页面

时间:2014-09-05 20:38:30

标签: javascript php jquery html

这是我在本网站的第一篇文章,希望有人可以提供帮助。

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

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

经过一些研究,我能找到的壁橱是这篇文章: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>

IN PAGE SCRIPT

<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代码中的最后一行。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

一些事情。

首先,您的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>
        }

请注意顶部只有一个<?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

答案 1 :(得分:0)

我会以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.
            }
        });
    });
}); 

页面不会重新加载,但返回的数据可以附加到页面,或者您可以制作并警告()

答案 2 :(得分:0)

好的,所以我想出来以防其他人有兴趣。

<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

感谢所有回复的人。