0

Basically, I am validating a sign-up form and calling a php script with ajax to check if an email address already exists or else the query executes. If an email address already exists (checked with a count query), I am echoing an error back to the ajax function (via response) - however it is not being read.

I tried researching similar topics but no luck.

ajax

$.ajax({
                type: 'POST',
                url: 'signup-user.php',
                dataType: 'text',
                data: $('form').serialize(),
                success: function(response) {

                        if(response == "error-email-exists"){
                            $('#errorMsg').html("An account is already assosciated with the email adress you entered.");
                            $('#errorMsg').hide().stop(true,true).fadeIn(600);
                        }else if(response == "success"){
                            window.location = "index.php";
                        }else{
                            $('#errorMsg').html(response);
                            $('#errorMsg').hide().stop(true,true).fadeIn(600);
                        }


                }
            });

php


<?php
    session_start(); 
    include("conn.php");

    $post_firstName = $_POST['firstName'];
    $post_lastName = $_POST['lastName'];
    $post_dateofBirth = $_POST['dateofBirth'];
    $post_gender = $_POST['gender'];
    $post_propertyNo = $_POST['propertyNo'];
    $post_propertyAddress = $_POST['propertyAddress'];
    $post_streetAddress = $_POST['streetAddress'];
    $post_locality = $_POST['locality'];
    $post_email = $_POST['email'];
    $post_password = $_POST['password'];


    $checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');

    $checkexistsQuery->bind_param('s', $post_email); 
    $checkexistsQuery->execute();

    $checkexistsQuery->store_result();
    $checkexistsQuery->bind_result($countExists);
    $checkexistsQuery->fetch();

    if($countExists > 0){
        echo 'error-email-exists';
    }else{
        $signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');

        $signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password); 

        if($signupQuery->execute()){
            echo 'success';
        }else{
            echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }


    }

?>









The problem is that 'error-email-exists' and 'success' messages are not being read.

6
  • What do you mean it's "not being read"? What specifically is happening? Commented Sep 18, 2019 at 10:15
  • If there is really a new line before <?php then some datas are sent before anything (and the response will be different than 'error-email-exists' Commented Sep 18, 2019 at 10:19
  • What is the result of console.log(response) ? Commented Sep 18, 2019 at 10:19
  • Write next to success block an error: function(error) { console.log(error)} block to be sure success is entered. Commented Sep 18, 2019 at 10:22
  • 2
    Check that there's no whitespace being returned, as this will break your response == "error-email-exists" check. It's for this reason it's much better practice to return a serialised response format. A quick fix would be response.trim() === 'error-email-exists', however I'd suggest using JSON instead to avoid the problem entirely. Commented Sep 18, 2019 at 10:23

1 Answer 1

1

Refactor your code as below. Use json type as contentType and add an error method to your ajax. With json you will be more flexible and have the opportunity to add structured data like errors, messages and even markup.

js:

$.ajax({
    type: 'POST',
    url: 'signup-user.php',
    dataType: 'json',
    data: $('form').serialize(),
    success: function (response) {
        if (response.error) {
            $('#errorMsg').html(response.message);
            $('#errorMsg').hide().stop(true, true).fadeIn(600);
        } else {
            if (response.exists) {
                $('#errorMsg').html("An account is already assosciated with the email adress you entered.");
                $('#errorMsg').hide().stop(true, true).fadeIn(600);
            } else {
                window.location = "index.php";
            }
        }
    },
    error: function (error) {
        console.log(error);
    }
});

php:

<?php
    session_start(); 
    include("conn.php");

    $post_firstName = $_POST['firstName'];
    $post_lastName = $_POST['lastName'];
    $post_dateofBirth = $_POST['dateofBirth'];
    $post_gender = $_POST['gender'];
    $post_propertyNo = $_POST['propertyNo'];
    $post_propertyAddress = $_POST['propertyAddress'];
    $post_streetAddress = $_POST['streetAddress'];
    $post_locality = $_POST['locality'];
    $post_email = $_POST['email'];
    $post_password = $_POST['password'];


    $checkexistsQuery = $conn->prepare('SELECT count(*) AS countExists FROM tbl_account acc WHERE acc.email = ?');

    $checkexistsQuery->bind_param('s', $post_email); 
    $checkexistsQuery->execute();

    $checkexistsQuery->store_result();
    $checkexistsQuery->bind_result($countExists);
    $checkexistsQuery->fetch();

    $response = [];
    $response['error'] = false;

    if($countExists > 0){
        $response['exists'] = true;
    }else{
        $signupQuery = $conn->prepare('insert into tbl_account (name, surname, email, password, dob, genderID, propertyNumber, propertyAddress, streetAddress, localityID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');

        $signupQuery->bind_param('ssssssssss', $post_firstName,$post_lastName,$post_dateofBirth,$post_gender,$post_propertyNo,$post_propertyAddress,$post_streetAddress,$post_locality,$post_email,$post_password); 

        if($signupQuery->execute()){
            $response['exists'] = false;
        }else{
            $response['error'] = true;
            $response['message'] = "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
        }
    }

    echo json_encode($response);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Edit: This does not work accordingly and is returning : prntscr.com/p7p0ub on console
Sorry. There was a typo missing $ -> echo json_encode($response);. I updated the answer.
Thank you! One quick question - is the response['error'] ambigious since if errors are handled by error: function(error)??
No. This name is up to you. function(error) fires when the response status is not 200 (error by the server e.g. status 500).

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.