1

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

7
  • Ajax has an option called succes. Its being executed as soon as the ajax call returns a positive input. Put your items from done there. I dont think you can call your data line outside the ajax call, cause thats what you did. Commented Dec 4, 2014 at 7:25
  • Try to Console.log(formData); Commented Dec 4, 2014 at 7:27
  • php code is now there. Commented Dec 4, 2014 at 7:29
  • @Indrasinh Bihola I have put a console.log of formData and it is populated correctly. The request gets to the PHP and it makes it into the database. I am just not getting the response text back in the data variable. Commented Dec 4, 2014 at 7:33
  • @Dorvalla I have tried both .done(function(data) and success: function(data And I'm not getting the info in data. Commented Dec 4, 2014 at 7:38

1 Answer 1

1

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'
    };
Sign up to request clarification or add additional context in comments.

3 Comments

but he said he is getting inserts.
I don't believe him. There's no way any of the code inside that if will be executed if he doesn't add that field.
@Barmar Thank you very much for looking past my assertions. I had a problem with not having data in the success item. It didn't show up when using the html post as it does get filled in. I mistakenly assumed it was going in via ajax as well. Ughh... the computer does exactly what you tell it to do. My assumed inserts that worked where when I reverted back to the HTML form post not the AJAX. If I could give you two green checks I would. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.