0

I am currently attempting to send form data via ajax to a php function but it does not appear to be sending it.

This is the HTML Form:

<form onSubmit="return registration();" id="registration_form">
    <input type="email" id="email_address" name="email_address" class="inputTextFooter">
    <input src="images/go.png" alt="Go" type="submit">
</form>

The AJAX:

function registration(){
    if(!$('#email_address').val()){
        alert("Empty");
    }
    else {
        $.ajax( {
            type: "POST",
            url: "includes/registration_check.php",
            data: $('#registration_form').serialize(),
            success: function( response ) {
                alert( response );
            }
        });
    }
    return false;
};

Finally the PHP:

$user_id = NULL;
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$distinct_query = "SELECT distinct user_email FROM user_emails";

$result=mysql_query($distinct_query, $connection);
$rows = mysql_num_rows($result) - 1;
$distinct_result_array = array();
while($fetched_array = mysql_fetch_assoc($result)) 
{
    $distinct_result_array[] = $fetched_array;
}

for ($loop = 0; $loop <= $rows; $loop++) { 
    if (in_array($user_email, $distinct_result_array[$loop])) {
        echo "Email taken.";
        break;
    }
    else{

    }
}

$query = "INSERT INTO user_emails (user_id, user_email) VALUES ('".$user_id."', '".$user_email."')";
        mysql_query($query, $connection);
        echo "You have successfully registered and will be checked by administration.";

When I send the form it adds to the database but the email field is blank.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Martin
  • 25
  • 6

3 Answers3

0

Replace

$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';

With

if(empty($_POST['email_address']))
{
echo "error";
exit;
}
else
{
$user_email = $_POST['email_address'];
}

And I advice you Use mysqli instead of mysql, also validate user input before inserting into database.

N Kumar
  • 1,302
  • 1
  • 18
  • 25
0

your function should have event.preventDefault() to restrict default form submit action then only your ajax request get triggerred.

function registration(){
event.preventDefault();
    if(!$('#email_address').val()){
        alert("Empty");
    }
    else {
        $.ajax( {
            type: "POST",
            url: "includes/registration_check.php",
            data: $('#registration_form').serialize(),
            success: function( response ) {
                alert( response );
            }
        });
    }
    return false;
};
Karthick Kumar
  • 2,349
  • 1
  • 17
  • 30
-2

I think you might need to use PHP's parse_str() function to get serialized data

http://php.net/manual/en/function.parse-str.php

user1187347
  • 318
  • 3
  • 12