Search code examples
phpjqueryajaxformspreventdefault

Using JQuery AJAX to submit a form to PHP, return data is empty


When I run this code below, the "data" returned is an empty string "[]". (At least viewed through the Chrome Console Viewer)

If I comment out the "event.preventDefault();" line in the JS I get a page reload, as expected, and a JSON string with results that passes JSONLint. I know the PHP is working as I am getting new inserts into the mySQL database and the return values make sense.

Everything seems to run correctly even with "data" is returned empty... (i.e. I am getting the console.log of FIRST first and SECOND second followed by the empty string.) I just can't get the returned "data" values in the JS context.

I'm kinda new to web development, not to programming... but does anyone spot a rookie mistake? I have read over about 12 similar questions and tried many things, but nothing is helping...

Thanks in advance.

$(document).ready(function() {
    $('form').submit(function(event) {
        var formData = {
            'firstName': $('input[name=firstName]').val(),
            'lastName': $('input[name=lastName]').val(),
            'email': $('input[name=email]').val(),
            'password': $('input[name=password]').val()
        };

        $.ajax({
            type: 'POST',
            url: 'createaccount.php',
            data: formData,
            dataType: 'json'
        })
            .done(function(data) {
                console.log("SECOND");
                console.log(data);
            });
        
        console.log("FIRST");
        event.preventDefault();
    });
});
    input {
        border-radius: 5px;
        border-width: 1px;
        margin: 2px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

        <div class="row">
            <div class="col-lg-12 text-center">
                <div class="col-lg-4"></div>
                <div class="col-lg-4 text-right">
                <h1>Join website</h1>
                    <form action="createaccount.php" method="post">
                        <label>First Name:</label><input type="text" name="firstName" /><br/>
                        <label>Last Name:</label><input type="text" name="lastName" /><br/>
                        <label>Email:</Label><input type="email" name="email" /><br/>
                        <label>Password:</label><input type="password" name="password" /><br/>
                        <input type="submit" value="Sign Up" name="submit" />
                    </form>
                </div>
                <div class="col-lg-4"></div>
            </div>
        </div>

<?php 

    $firstName = $_POST["firstName"];
    $lastName = $_POST["lastName"];
    $email = $_POST["email"];
    $password = $_POST["password"];
    $submit = $_POST["submit"];

    $errors = array();
    $data = array();

    if ($submit) {  
        if (!$email) { 
            $errors['email'] = "Email is required.";
        } 
        else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['validemail'] = "Valid email is required.";
        }
        
        if (!$password) {
            $errors['password'] = "Password is required.";
        } 
        else {
            if (strlen($password) < 8) {
                $errors['passwordlength'] = "Password must be at least 8 characters long";
            }
            if (!preg_match("#[A-Z]+#", $password)) {
                $errors['passwordcaps'] = "Password must contain at least one Capital Letter";
            }
        } 
    
                    
        if (empty($errors)) {
                    
            require 'dbconnect.php';
            
            $query="SELECT * FROM Users WHERE email='".mysqli_real_escape_string($link, $email)."'";
            
            $result = mysqli_query($link, $query);
            
            $results = mysqli_num_rows($result);
                                                                                 
            if ($results) {
                $errors['exists'] = "That email address is already registered.";
            } 
            else {
                $firstName = mysqli_real_escape_string($link, $firstName);
                $lastName = mysqli_real_escape_string($link, $lastName);
                $email = mysqli_real_escape_string($link, $email);
                $password = md5(md5($email).$password);
            
                $query="INSERT INTO `Users` (`FirstName`, `LastName`, `Email`, `Password`, `IsRater`, `IsRatee`) VALUES('$firstName', '$lastName', '$email', '$password', '1', '1');";
            
                if(!mysqli_query($link, $query)) {
                    $errors['SQLQuery'] = "Failed SQL Insert" . mysqli_error($link);
                }
                else
                {
                    $data['success'] = true;
                    $data['message'] = 'Your account has been created!';
                }
            }
        }
        
        if(!empty($errors)) {
            $data['success'] = false;
            $data['errors'] = $errors;
        }
    }

    echo json_encode($data);
?>


Solution

  • The PHP code checks whether $_POST['submit'] is set before doing anything with the form data, but you never set that in formData. Try:

        var formData = {
            'firstName': $('input[name=firstName]').val(),
            'lastName': $('input[name=lastName]').val(),
            'email': $('input[name=email]').val(),
            'password': $('input[name=password]').val(),
            'submit': 'on'
        };