Lemoncide
Lemoncide

Reputation: 79

Data not being sent to a php form from a javascript function

I am trying to make a registration form using JavaScript and PHP but I'm encountering a problem. The JavaScript code does not send the array through to the register_submit.php . I've tried looking into a few examples on the internet and other posts on StackOverflow but none of the answers seemed to resolve my own issue.

The user comes to the registration.php page, fills out the form and hits the submit button which calls the checkForms() method. The setValues() method sets the values from the registration form to individual variables. I've checked if the variables retrieved are correct (they are).

EDIT: The issue is not the fact that there are two $password variables. Accidental testing error.

JavaScript code:

function checkForms() {
    setValues();
    callPHP();
}

function callPHP() {


    alert(registration.emailR);
        // call ajax
        $.ajax({
            type: "POST",
            url: 'register_submit.php',
            data:{name:registration.usernameR, email:registration.emailR, password:registration.password1R, forename:registration.forenameR, surname:registration.surnameR, country:registration.countryR, dob:registration.dobR},
            success:function(msg) {
                alert("Register Complete");    
            }    
        });

        // Go to homepage
        window.location.href = "index.php";

}

PHP code :

<?php
    $username = $_POST['username'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $forename = $_POST['forename'];
    $surname = $_POST['surname'];
    $country = $_POST['country'];
    $dob = $_POST['dob'];

    $host = "host";
    $user = "user";
    $password = "password";
    $database = "database";

$con = new mysqli($host, $user, $password, $database);

if(!$con)
    die('Connection failed'.mysql_error());
else echo "Connection successful  ";
mysqli_select_db($con, $database);

        $query = "INSERT INTO user (userID, username, dob, email, password, isAuthor, isAdmin, country, surname, firstname) VALUES ('user001', '$username', '$dob', '$email', '$password', '0', '0', '$country', '$surname', '$forename')";
        echo $query;
        mysqli_query($con, $query);
        echo "Registration Complete!!";
?>

Upvotes: 0

Views: 54

Answers (1)

razz
razz

Reputation: 10120

Ajax is asyncronous which means that it works in the background until the job is done, you are navigating away from the page before ajax is done with this line:

window.location.href = "index.php";

put it inside the success method:

success:function(msg)
{
    alert ("Register Complete");
    window.location.href = "index.php"; 
} 

Upvotes: 3

Related Questions