开发者

AJAX Email Signup Form + .htaccess Clean URLs problem

I've successfully installed this jQuery-based signup form here: http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/

But when I applied it to my main layout, which is PHP-based and uses clean URLs, the form works funky: I submit an email, and it stays at the "Please wait..." state. I'm guessing that it stops running the $.ajax({ line.

The JS code is as below:

<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'), 
                    开发者_如何学GoresponseMsg = $('#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>

The HTACCESS looks something like this:

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

Which passes the variables into index.php. In index.php, I split everything into an array, and parse the URL that way:

    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
}

I've been trying to troubleshoot this for hours and still have not found a solution.

Any hints/helpful info would be awesome.

/* EDIT: Included Firebug Analysis */

Thanks Nathan! I tried your suggestion and came up with the following error when I ran a test (tried submitting the form):

"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!"}"

It basically gives me the code for the entire page, all the way until the success message. The entry DOES appear in mysql successfully.

I think the problem is really the JSON being passed...which I'm not very familiar with at all. It seems to hiccup where htaccess/clean URL's occur.

I'm not sure where to go about fixing this. Do you have any suggestions?


Download Firebug from here: https://addons.mozilla.org/en-US/firefox/addon/firebug/

  • Install
  • Open Firefox and load your desired web page and click the little fire type beetle in the lower right hand corner of the browser window

AJAX Email Signup Form + .htaccess Clean URLs problem

You then need to select the console tab and refresh your website so that the console loads correctly, all you need to do now is watch the console once you have requested your ajax action from your app!

AJAX Email Signup Form + .htaccess Clean URLs problem

You will see a loading bar appear with either GET or POST (depending on what form method you have in place), this will be able to tell you what data has been sent and any errors from the php file.


Error is not in your javascript it is because of the php page that you have in the action attribute of the form. you have printed the json after doc type tag. remove the doctype tag and try. let me know if still have the problem.

The response should contain only json like this.

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


Put the PHP code from the tutorial at the very top of your document.

Make sure this code STARTS your document, and does not come after any of the jQuery, HTML, CSS, etc.

<?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;
    }
    ?>


The problem seems to be that your response includes the HTML from a page, which is invalid JSON code. Make sure the response only includes this:

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

Your code also includes the HTML, like the DOCTYPE header you posted in the example.

Without seeing the code on the response page, it's difficult to advise on how to remove the HTML.

Hope this is helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜