Error: Invalid character encountered during login script JSON parsing

I found this script online and have been experimenting with it. However, I encountered the following error:

SyntaxError: JSON.parse: unexpected character

[Break On This Error]

var res = JSON.parse(result);

The problem lies in the file below as I am unfamiliar with JSON operations.

Error-causing file: register.js

$(document).ready(function () {
//button register click
$("#btn-register").click(function () {
    if(register.validateRegistration() === true) {
        //validation passed
        var regMail     = $("#reg-email").val(),
            regUser     = $("#reg-username").val(),
            regPass     = $("#reg-password").val(),
            regPassConf = $("#reg-repeat-password").val(),
            regBotSsum  = $("#reg-bot-sum").val();

        //create data that will be sent to server
        var data = { 
            userData: {
                email           : regMail,
                username        : regUser,
                password        : regPass,
                confirm_password: regPassConf,
                bot_sum         : regBotSsum
            },
            fieldId: {
                email           : 'reg-email',
                username        : 'reg-username',
                password        : 'reg-password',
                confirm_password: 'reg-repeat-password',
                bot_sum         : 'reg-bot-sum'
            }
        };

        //send data to server
        register.registerUser(data);
    }                        
});
});



/** REGISTER NAMESPACE
 ======================================== */

var register = {};


/**
 * Registers new user.
 * @param {Object} data Register form data.
 */
register.registerUser = function (data) {
//get register button
var btn = $("#btn-register");

//put button to loadin state
asengine.loadingButton(btn, "Creating acount...");

//hash passwords before send them through network
data.userData.password = CryptoJS.SHA512(data.userData.password).toString();
data.userData.confirm_password = CryptoJS.SHA512(data.userData.confirm_password).toString();

//send data to server
$.ajax({
    url: "ASEngine/ASAjax.php",
    type: "POST",
    data: {
        action  : "registerUser",
        user    : data
    },
    success: function (result) {
        //return button to normal state
        asengine.removeLoadingButton(btn);

        //parse result to JSON
        var res = JSON.parse(result);

        if(res.status === "error") {
            //error

            //display all errors
            for(var i=0; i<res.errors.length; i++) {
                var error = res.errors[i];
                asengine.displayErrorMessage($("#"+error.id), error.msg);
            }
        }
        else {
            //display success message
            asengine.displaySuccessMessage($(".register-form fieldset"), res.msg);
        }
    }
});
};



register.validateRegistration = function () {
var valid = true;

//remove previous error messages
asengine.removeErrorMessages();


//check if all fields are filled
$(".register-form").find("input").each(function () {
    var el = $(this);

    if($.trim(el.val()) === "") {
        asengine.displayErrorMessage(el);
        valid = false;
    }
});

//get email, password and confirm password for further validation
var regMail     = $("#reg-email"),
    regPass     = $("#reg-password"),
    regPassConf = $("#reg-repeat-password");

//check if email is valid
if(!asengine.validateEmail(regMail.val()) && regMail.val() != "") {
    valid = false;
    asengine.displayErrorMessage(regMail,"Please insert valid email.");
}

//check if password and confirm password fields are equal
if(regPass.val() !== regPassConf.val() && regPass.val() != "" && regPassConf.val() != "") {
    valid = false;
    asengine.displayErrorMessage(regPassConf, "Passwords don't match.");
}

return valid;
};

ASRegister.php

<?php

/**
 * User registration class.
 *
 */
class ASRegister extends ASDatabase{

//local ASEmail object
private $mailer;

function __construct() {

    //connect to database
    parent::__construct(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS);

    //create new object of ASEmail class
    $this->mailer = new ASEmail();
}

/**
 * Register user.
 * @param array $data User details provided during the registration process.
 */
public function register($data) {
    $user = $data['userData'];

    //validate provided data
    $errors = $this->_validateUser($data);

    if(count($errors) == 0) {
        //no validation errors

        //generate email confirmation key
        $key = $this->_generateKey();

        //insert new user to database
        $this->insert('as_users', array(
            "email"     => $user['email'],
            "path"      => strtolower(str_replace(' ','',$name)),
            "username"  => strip_tags($user['username']),
            "password"  => $this->hashPassword($user['password']),
            "confirmation_key"  => $key,
            "register_date"     => date("Y-m-d")     
        ));

        //send confirmation email
        $this->mailer->confirmationEmail($user['email'], $key);

        //prepare and output success message
        $result = array(
            "status" => "success",
            "msg"    => SUCCESS_REGISTRATION
        );

        echo json_encode($result);

    }
    else {
        //there are validation errors

        //prepare result
        $result = array(
            "status" => "error",
            "errors" => $errors
        );

        //output result
        echo json_encode ($result);
    }
}

/**
 * Check if user with given username exist.
 * @param string $username Given username.
 * @return boolean TRUE if user already exist, false otherwise.
 */
public function doesUserExist($username) {
    if(!$this->_isUsernameAvailable($username))
        return true;
    return false;
}


/**
 * Check if email already exist in database.
 * @param string $email Email to check.
 * @return boolean TRUE if email exist, FALSE otherwise
 */
public function doesEmailExist($email) {
    return !$this->_isEmailAvailable($email);
}


/**
 * Send forgot password email.
 * @param string $userEmail Provided email.
 */
public function forgotPassword($userEmail) {
    //we only have one field to validate here
    //so we don't need id's from other fields
    if($userEmail == "")
        $errors[] = ERROR_EMAIL_REQUIRED;
    if(!$this->_validateEmail($userEmail))
        $errors[] = ERROR_EMAIL_WRONG_FORMAT;

    if($this->doesEmailExist($userEmail) == false)
        $errors[] = ERROR_EMAIL_NOT_EXIST;

    if(count($errors) == 0) {
        //no validation errors

        //generate password reset key
        $key = $this->_generateKey();

        //write key to db
        $this->update(
                    'as_users', 
                     array("password_reset_key" => $key), 
                     "`email` = :email",
                     array("email" => $userEmail)
                );

        //send email
        $this->mailer->passwordResetEmail($userEmail, $key);
    }
    else
        echo json_encode ($errors); //output json encoded errors
}


/**
 * Reset user's password if password reset request has been made.
 * @param string $newPass New password.
 * @param string $passwordResetKey Password reset key sent to user
 * in password reset email.
 */
public function resetPassword($newPass, $passwordResetKey) {
    $pass = $this->hashPassword($newPass);
    $this->update(
                'as_users', 
                array("password" => $pass), 
                "`password_reset_key` = :prk ",
                array("prk" => $passwordResetKey)
            );
}


/**
 * Hash given password.
 * @param string $password Unhashed password.
 * @return string Hashed password.
 */
 public function hashPassword($password) {
    //this salt will be used in both algorithms
    //for bcrypt it is required to look like this,
    //for sha512 it is not required but it can be used 
    $salt = "$2a$" . PASSWORD_BCRYPT_COST . "$" . PASSWORD_SALT;

    if(PASSWORD_ENCRYPTION == "bcrypt") {
        $newPassword = crypt($password, $salt);
    }
    else {
        $newPassword = $password;
        for($i=0; $i<PASSWORD_SHA512_ITERATIONS; $i++)
            $newPassword = hash('sha512',$salt.$newPassword.$salt);
    }

    return $newPassword;
 }


/**
 * Generate two random numbers and store them into $_SESSION variable.
 * Numbers are used during the registration to prevent bots to register.
 */
 public function botProtection() {
    ASSession::set("bot_first_number", rand(1,9));
    ASSession::set("bot_second_number", rand(1,9));
}


 /* PRIVATE AREA
 =================================================*/


/**
 * Validate user provided fields.
 * @param array $data User provided fieds and id's of those fields that will 
 * be used for displaying error messages on client side.
 * @return array Array with errors if there are some, empty array otherwise.
 */
private function _validateUser($data) {
    $id     = $data['fieldId'];
    $user   = $data['userData'];
    $errors = array();

    //check if email is not empty
    if($user['email'] == "")
        $errors[] = array( 
            "id"    => $id['email'],
            "msg"   => ERROR_EMAIL_REQUIRED 
        );

    //check if username is not empty
    if($user['username'] == "")
        $errors[] = array( 
            "id"    => $id['username'],
            "msg"   => ERROR_USERNAME_REQUIRED
        );

    //check if password is not empty
    if($user['password'] == "")
        $errors[] = array( 
            "id"    => $id['password'],
            "msg"   => ERROR_PASSWORD_REQUIRED
        );

    //check if password and confirm password are the same
    if($user['password'] != $user['confirm_password'])
        $errors[] = array( 
            "id"    => $id['confirm_password'],
            "msg"   => ERROR_PASSWORDS_DONT_MATCH
        );

    //check if email format is correct
    if(!$this->_validateEmail($user['email']))
        $errors[] = array( 
            "id"    => $id['email'],
            "msg"   => ERROR_EMAIL_WRONG_FORMAT
        );

    //check if email is available
    if($this->_isEmailAvailable($user['email']) == false)
        $errors[] = array( 
            "id"    => $id['email'],
            "msg"   => ERROR_EMAIL_TAKEN
        );

    //check if username is available
    if($this->_isUsernameAvailable($user['username']) == false )
        $errors[] = array( 
            "id"    => $id['username'],
            "msg"   => ERROR_USERNAME_TAKEN
        );

    //bot protection
    $sum = ASSession::get("bot_first_number") + ASSession::get("bot_second_number");
    if($sum != intval($user['bot_sum']))
        $errors[] = array( 
            "id"    => $id['bot_sum'],
            "msg"   =>ERROR_WRONG_SUM
        );


    return $errors;
}


/**
 * Check if email is available.
 * @param string $email Email to be checked.
 * @return boolean TRUE if email is available, FALSE otherwise
 */
private function _isEmailAvailable($email) {
    $query = "SELECT * FROM `as_users` WHERE `email` = :e ";
    $result = $this->select($query, array( "e" => $email ));
    if(count($result) == 0)
        return true;
    else
        return false;
}


/**
 * Check if username is available.
 * @param string $un Username to check.
 * @return boolean TRUE if username is available, FALSE otherwise.
 */
private function _isUsernameAvailable($un) {
    $query = "SELECT * FROM `as_users` WHERE `username` = :u ";
    $result = $this->select($query, array( "u" => $un ));
    if(count($result) == 0)
        return true;
    else
        return false;
}


/**
 * Check if email has valid format.
 * @param string $email Email to be checked.
 * @return boolean TRUE if email has valid format, FALSE otherwise.
 */
private function _validateEmail($email) {
    return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i", $email);
}


/**
 * Generate key used for confirmation and password reset.
 * @return string Generated key.
 */
private function _generateKey() {
    return md5(time() . LOGIN_SALT . time());
}


}

?>

Answer №1

Make sure to validate the JSON response being sent from the server by using a tool like http://jsonlint.com/. Don't forget to double-check for any missing commas or other syntax errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

Execute a jQuery focus() function on a textarea element within a dynamically added form on the webpage

Whenever I dynamically insert a new form onto the page using clone(), my goal is to have the textarea within the form automatically focused. However, despite trying out the code below, it seems like it's not functioning as expected: .on('click&a ...

Simple Java methods for organizing and finding information in a json array

Here is an example of my Json file structure: { "Hello" : [{ "CommentId":28227, "Comments":"User Philip John has added a new file", "DisplayComments":"User <a id='getUser' data='205' >Philip John</a> has a ...

The JSON object was not found in the AJAX response

I received a JSON object through an AJAX request. When I use console.log(response); in the console, I can see my object. However, when I use console.log(response.mostSearched);, it returns undefined. Why is that? I copied the object from the devTools con ...

Using node modules within an HTML document

I'm finding it challenging to understand how npm handles dependencies when it comes to referencing them in HTML. For example, if I have a specific version of a plugin installed that includes the version number in its path or file name, and npm is set ...

Tips on utilizing innerHTML or innerText to add content to the Evernote editor, a rich text editor

A method authored by Jayant was employed in this particular post how-to-insert-text-into-the-textarea-at-the-current-cursor-position to perform an insertion into the Evernote editor. The Evernote editor being a rich text editor, altering from el.value to ...

Using NodeJs to Render HTML Templates and Implement Logic on the Server Side

Hello, I am currently working on developing a widget module for my Angular 1 based UI project. This widget is meant to display real-time information. My design involves sending an HTML view to the client from the Node server (potentially using Express.js) ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

JavaScript code to obscure

My goal is to create a JavaScript function where the "costCenter" object starts with visibility set to false. However, when the user clicks on the "computer" item in a dropdown list, the visibility of "costCenter" should change to true. This is my current ...

JavaScript Function or Object: A Guide to Returning

Currently, my code is functioning as expected. However, I am curious if there is a way to modify my function so that it can be declared as an object even when no parameters are provided. Below is the mixin function in question: import Page from "@/models ...

Custom AngularJS directive for ensuring the selection of a required HTML element

Today brings another question as I continue working on my web application. I've encountered an issue with the 'required' attribute not being widely supported in major browsers. The attribute only works if the first option value is empty, whi ...

Unspecified data returned from PHP script via jQuery AJAX

Encountering an issue while trying to use AJAX to get a PHP response from a form. The JavaScript appears to be correct as it functions when the content of login_ajax.php is reduced to just: echo 'CORRECT' //or echo 'INCORRECT' Howev ...

How can I improve my skills in creating efficient Angular routers?

In my Ionic project, I am dealing with an AngularJS routes file that contains a large number of routes, approximately a hundred. The structure is similar to the one provided below. (function() { 'use strict'; angular.module('applicatio ...

In search of a new object value to update

Looking to update the value of a specific object key in an array? Here is the code snippet where I want to make this change. I only want to replace the value under Mon, not the entire array length. The key weekday will be provided dynamically. array = [ ...

React is unable to identify the prop `controlID` when used on a DOM element in React-Bootstrap Forms

While constructing a form with React components sourced from react-bootstrap, and taking guidance directly from an example provided in its documentation: <Form.Group controlId="formBasicEmail"> <Form.Label>Email address</Form.Label> ...

What is the best way to designate external dependencies in WebPack that are not imported using '*'?

I need assistance with specifying office-ui-fabric-react as an external dependency in my TypeScript project using Webpack. Currently, I am importing only the modules I require in my project: import { Dialog, DialogType, DialogFooter } from 'office-u ...

I am facing issues with running my project due to a gyp error. Can anyone provide guidance on resolving this problem?

Every time I execute my code, I encounter the same persistent error. Despite attempting to resolve it by uninstalling and reinstalling Node and npm, the issue persists. Furthermore, the lack of "node_modules" exacerbates the problem. How can I rectify this ...

The Owl-Carousel's MouseWheel functionality elegantly navigates in a singular, seamless direction

Issue at Hand: Greetings, I am facing a challenge in constructing a carousel using Owl-Carousel 2.3.4. My goal is to enable the ability to scroll through my images using the mousewheel option. Code Implementation: Incorporating HTML code : <div style ...

Retrieve the following and previous JSON object

Is there a way to retrieve the next object (with Id 120) and the previous object (with Id 122) when currently at the second object with Id 141? I also have control over the JSON format. var articleId = 141; var url = { "Article": [ { ...

Executing callback functions after numerous asynchronous calls have been completed

Is there a method to delay the execution of a specific line of code until multiple API calls have all returned? Typically, I follow this pattern: APIService.call(parameter).then(function(response) { // Do something callBack(); }); This approach wo ...