views:

52

answers:

3

Here's my form:

<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<input id="submit" type="submit" name="submit" value="Go!" />
</form>

And my jQuery:

    $(document).ready(function() {

        $('form').submit(function() {
            email = $('input[name=email]').val();
            $.post("/scripts/addemail.php", {email_address:email}, function(data){

               if(data == "invalid") { 
                alert("invalid"); 

               } else if(data == "used") { 
                alert("used"); 

               } else if(data == "success") { 
               alert("success"); 

               } else {
                alert("error"); 

               }
            });
        });
    });

and my PHP:

<?php

mysql_connect ('localhost', '********', '********') ;
mysql_select_db ('Blog');

function check_email($input) {

     $input = htmlspecialchars(strip_tags($input));

     $checkaddress = "SELECT * FROM emails WHERE email='$input'"; 
     $query = mysql_query($checkaddress);

     if (!eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $input)) {
          return "invalid";
     } else if ( mysql_num_rows($query) >= 1 ) { 
        return "used"; 
     } else {
        $result = mysql_query("INSERT INTO emails (email) VALUES ('$input')");
        return "success";
    }
}

$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>

The problem is that its going to the action="/scripts/addemail_fb.php" instead of the jQuery. I'm new to AJAX, and AJAX with jQuery, but I've been using jQuery for quite some time.

I think there are two problems: I don't think that the information is being sent to the jQuery correctly, and I'm not sure how to deal with the key:value pairs (email_address:email) in PHP. Thanks for any help! And yes, I'm obviously a beginner.

+5  A: 

add a return false; inside the form's submit function to prevent default behavior.

czarchaic
+1  A: 

Consider changing your input of type "submit" to "button". Then add your jquery code to the "onclick" event for that button. so..instead of "$('form').submit()..." you should use

$("#nameofSubmitButton").click(function(){
 //do your stuff here.
});
oneBelizean
A: 

You need an onSubmit event handler, either explicitly in the form tag, or implicitly attached to it via DOM/jquery, pointing to your function.

AJ