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

Retrieve the minimum and maximum values from a multi-dimensional array

If my array consists of the following subarrays: array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] I am looking to determine the maximum and minimum values in this array. For example, in this case: max = 33, min = 0 While I have come across exampl ...

Struggling to decipher JSON using jQuery proved to be quite challenging

JSON object (parameters) "selectedShopeNumber":1765653589, "shopeNumbersForSelectedNames":[], "shopeNumbers":[1765653589, 660791222],"shopeNames":["Shope 1","Shope 2"] code var params = JSON.parse("[" + parameters + "]"); for (var i = 0; i < params.s ...

Adjusting the background hue of the 'td' element within an ajax request

When I press a button, an ajax call is triggered below. In this call, I append 'td' elements with values to a table. Specifically, on the line ''</td><td>' + result[i].preRiskCategory +', I am attempting to change ...

Including a fresh JSON entity into an array within a file

I am working with a JSON file that contains an array of objects under "NavigationControls". My goal is to add a new item to this array and update the file. I would appreciate any tips or guidance on how to achieve this. Thank you! { "LocalId": "sect ...

PUPPETER - Unpredictable pause in loop not functioning as expected

Having an issue with this specific part of the code: (async () => { const browser = await puppeteer.launch({ headless: false, // slowMo: 250 // slow down by 250ms }); const page = await browser.newPage(); //some code // CODE ABOVE WORKS, ...

Guide on configuring and executing AngularJS Protractor tests using Jenkins

I am encountering an error with the following configuration: ERROR registration capabilities Capabilities [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] does not match the current platform LINUX 18:17:05.892 INFO ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Obtaining Runtime Inputs from the Command Line

I have been using a unique Vue SPA boilerplate found at this link, which utilizes webpack as its foundation. During the development process or when deploying the application, I have successfully utilized process.env.NODE_ENV to differentiate between a dev ...

Incorporate additional JSON data dynamically into a listview by scrolling, leveraging the features of the Volley

element, I attempted to follow the tutorial provided in the link below to create an endless scrolling list. However, I am struggling with the implementation of the customLoadMoreDataFromApi(int page) method mentioned in the tutorial. The JSON Request and ...

obtain data from an array using Angular 5

i need assistance with retrieving values from an array. Below is my code snippet: this.RoleServiceService.getRoleById(this.id).subscribe(data => { this.roleData.push(data['data']); console.log(this.roleData); }) however, the resulting ar ...

Guidelines for calculating the CRC of binary data using JQuery, javascript, and HTML5

Can you please assist me with the following issue? Issue: I am currently reading file content using the HTML5 FileReaderAPI's ReadAsArrayBuffer function. After storing this buffer in a variable, I now need to compute the CRC (Cyclic Redundancy Check) ...

JSON is not conforming to the standard nesting level

After simplifying, the JSON implementation is as follows: Data(Entity)->"data"->another Entity I originally thought I could decrypt the Data object first, extract a type from it, and then use that type to decrypt the necessary type from the String "d ...

Using the typeahead feature to retrieve a value and then incorporating it into an ajax

Currently, I am utilizing the jQuery typeahead plugin for ajax search functionality. In the provided demo, all the data sources are linked to a json file and retrieved from there. However, in my scenario, I am using a php file as the data source. Within ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

Customizing React component properties within a Styled Component

I have been experimenting with styled components to customize the appearance of basic material-ui React components. My goal is to pass props into the MUI component and then use styled components to apply CSS styling. One interesting aspect is being able t ...

Creating multiple Google markers based on addresses retrieved from a database using PHP

I have a requirement to display multiple Google markers on a map based on addresses stored in a database. I have already successfully loaded an XML file to retrieve latitude and longitude coordinates, but now I need assistance on how to create multiple m ...

React unit tests experiencing issues with MSW integration

After creating a basic React application, I decided to configure MSW based on the instructions provided in order to set it up for unit tests in both node environment and browser. The main component of the app utilizes a custom hook called useFormSubmission ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...

What are the benefits of using "var self = this" for synchronizing between a class and events?

Consider this straightforward code example (it's in AngularJS for simplicity, but the scenario is common in JavaScript): angular.module('app',[]). directive('myDir', function(){ this.state = {a:1, b:2}; return { l ...

Only the initial AJAX request is successful, while subsequent requests fail to execute

I am facing an issue with multiple inputs, each requiring a separate AJAX request. < script type = "text/javascript" > $(document).ready(function() { $("#id_1").change(function() { var rating1 = $(this).v ...