AJAX电子邮件注册表单+ .htaccess清除URL问题

时间:2011-02-26 00:57:44

标签: php jquery mysql forms newsletter

我在这里成功安装了这个基于jQuery的注册表单: http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/

但是当我将它应用到我的主要布局(基于PHP并使用干净的URL)时,表单工作时髦: 我提交了一封电子邮件,它处于“请等待......”状态。 我猜它停止了$.ajax({行。

JS代码如下:

<script type="text/javascript">
    // code using jQuery
    $(document).ready(function(){

        $('#newsletter-signup').submit(function(){

            //check the form is not currently submitting
            if($(this).data('formstatus') !== 'submitting'){

                //setup variables
                var form = $(this),
                    formData = form.serialize(),
                    formUrl = form.attr('action'),
                    formMethod = form.attr('method'), 
                    responseMsg = $('#signup-response');

                //add status data to form
                form.data('formstatus','submitting');

                //show response message - waiting
                responseMsg.hide()
                           .addClass('response-waiting')
                           .text('Please Wait...')
                           .fadeIn(200);

                //send data to server for validation
                $.ajax({
                    url: formUrl,
                    type: formMethod,
                    data: formData,
                    success:function(data){

                        //setup variables
                        var responseData = jQuery.parseJSON(data), 
                            klass = '';

                        //response conditional
                        switch(responseData.status){
                            case 'error':
                                klass = 'response-error';
                            break;
                            case 'success':
                                klass = 'response-success';
                            break;  
                        }

                        //show reponse message
                        responseMsg.fadeOut(200,function(){
                            $(this).removeClass('response-waiting')
                                   .addClass(klass)
                                   .text(responseData.message)
                                   .fadeIn(200,function(){
                                       //set timeout to hide response message
                                       setTimeout(function(){
                                           responseMsg.fadeOut(200,function(){
                                               $(this).removeClass(klass);
                                               form.data('formstatus','idle');
                                           });
                                       },3000)
                                    });
                        });
                    }
                });
            }

            //prevent form from submitting
            return false;
        });
    });

 // end noConflict wrap
</script>

HTACCESS看起来像这样:

<IfModule mod_rewrite.c>

    RewriteEngine On

    # COMPANY NAVIGATION

        #Sends URI to index.php for parsing
        RewriteRule !\.(css|gif|jpg|png|ico|txt|xml|js|pdf|htm|zip)$ /path/to/main/folder/index.php [NC]

</IfModule>

将变量传递给index.php。在index.php中,我将所有内容拆分为一个数组,并以这种方式解析URL:

    function create_url_array($url) {
        strip_tags($url);
        $url_array = explode("/", $url);
        array_shift($url_array); // First one is empty
        return $url_array;
    }
    $url = $_SERVER['REQUEST_URI'];
    $url_array = create_url_array($url);

if($url_array[1] == "folder") { 
// include relevant page/s etc
}

我一直试图对此进行数小时的排查,但仍未找到解决方案。

任何提示/有用的信息都会很棒。

/ *编辑:包含的Firebug分析* /

谢谢内森!我尝试了你的建议,并在我运行测试时尝试了以下错误(尝试提交表单):

"uncaught exception: Invalid JSON: 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
... 
{"status":"success","message":"You have been signed up!"}"

它基本上为我提供了整个页面的代码,一直到成功消息。条目DOES成功出现在mysql中 我认为问题实际上是传递的JSON ......我根本不熟悉它。似乎打嗝htaccess / clean URL的出现。
我不知道该怎么做才能解决这个问题。你有什么建议吗?

4 个答案:

答案 0 :(得分:1)

从这里下载Firebug:https://addons.mozilla.org/en-US/firefox/addon/firebug/

  • 安装
  • 打开Firefox并加载您想要的网页,然后点击浏览器窗口右下角的小火型甲虫

Firebug Icon

然后,您需要选择控制台选项卡并刷新您的网站,以便控制台正确加载,您现在需要做的就是在您从应用程序请求ajax操作后观看控制台! Console Tab

你会看到一个带有GET或POST的加载栏(取决于你所使用的表格方法),这将能够告诉你已经发送了什么数据以及php文件中的任何错误。

答案 1 :(得分:1)

错误不在你的javascript中,因为你在表单的action属性中有php页面。你已经在doc类型标签后打印了json。删除doctype标记并尝试。让我知道是否还有问题。

响应应该只包含这样的json。

{"status":"success","message":"You have been signed up!"}

答案 2 :(得分:1)

将教程中的PHP代码放在文档的最顶层。

确保此代码 STARTS 您的文档,并且不会出现在任何的jQuery,HTML,CSS等

<?php
//email signup ajax call
if($_GET['action'] == 'signup'){

mysql_connect('localhost','YOUR DB USERNAME','YOUR DB PASSWORD');  
mysql_select_db('YOUR DATABASE THAT CONTAINS THE SIGNUPS TABLE');

//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);

//validate email address - check if input was empty
if(empty($email)){
    $status = "error";
    $message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\@[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
        $status = "error";
        $message = "You have entered an invalid email address!";
}
else {
    $existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");   
    if(mysql_num_rows($existingSignup) < 1){

        $date = date('Y-m-d');
        $time = date('H:i:s');

        $insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
        if($insertSignup){ //if insert is successful
            $status = "success";
            $message = "You have been signed up!";  
        }
        else { //if insert fails
            $status = "error";
            $message = "Ooops, Theres been a technical error!"; 
        }
    }
    else { //if already signed up
        $status = "error";
        $message = "This email address has already been registered!";
    }
}

//return json response
$data = array(
    'status' => $status,
    'message' => $message
);

echo json_encode($data);
exit;
    }
    ?>

答案 3 :(得分:0)

问题似乎是您的响应包含来自页面的HTML,这是无效的JSON代码。确保响应仅包括:

{"status":"success","message":"You have been signed up!"}

您的代码还包含HTML,例如您在示例中发布的DOCTYPE标题。

如果没有在响应页面上看到代码,就很难建议如何删除HTML。

希望这有用。