Uncaught Syntaxerror: Unexpected Token with JSON.Parse

Error Uncaught SyntaxError: Unexpected token with JSON.parse

products is an object. (creating from an object literal)

JSON.parse() is used to convert a string containing JSON notation into a Javascript object.

Your code turns the object into a string (by calling .toString()) in order to try to parse it as JSON text.

The default .toString() returns "[object Object]", which is not valid JSON; hence the error.

SyntaxError: Unexpected token in JSON at position 0

The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). I know you said the server is setting Content-Type:application/json, but I am led to believe the response body is actually HTML.

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"

with the line console.error(this.props.url, status, err.toString()) underlined.

The err was actually thrown within jQuery, and passed to you as a variable err. The reason that line is underlined is simply because that is where you are logging it.

I would suggest that you add to your logging. Looking at the actual xhr (XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText) and you will most likely see the HTML that is being received.

JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0`

You have a strange char at the beginning of the file.

data.charCodeAt(0) === 65279

I would recommend:

fs.readFile('addresses.json', function (err, data) {
if (data) {
console.log("Read JSON file: " + data);
data = data.trim();
//or data = JSON.parse(JSON.stringify(data.trim()));
storage = JSON.parse(data);
}});

Uncaught SyntaxError: Unexpected token ' in JSON at position 2

This is not valid json string. Its values and keys should be surrounded with double quotes (not single). So when you do .replace(/"/g, "'") you basically break the JSON standard.

A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.

Uncaught SyntaxError: Unexpected token in JSON at position 0 at JSON.parse - Wordpress

Ok so this should do what you're looking for. I've rewritten your code for better WordPress integration.

First, you'll need to create a new javascript file name visitor-counter.js and place it a js folder in your themes directory. This will be used for our jQuery and ajax request.

/js/visitor-counter.js

(function($) {

window.VisitorCounter = window?.VisitorCounter || {

/**
* @type {object} Temp storage object
*/
_temp: {},

/**
* Get a PHP variable.
*
* @param varName
* @returns {*}
*/
getVar(varName) {
const vars = window?.VisitorCounterVars;
return vars?.[varName];
},

/**
* Make ajax request to server, store response in temp object.
*
* @returns {Promise<unknown>}
*/
request() {
return new Promise((accept, reject) => {
const url = this.getVar('ajaxUrl');
const action = this.getVar('ajaxAction');
const post_id = this.getVar('post_id');

if (url && action) {
$.ajax({
url: url,
data: {
action: action,
post_id: post_id
},
cache: false
}).then(response => {
this._temp.count = response.data;
accept(response);
console.log(response);
});
} else {
reject('Visitor counter ajax url or action not available.');
}
});
},

/**
* Get the count value.
*
* @returns {number}
*/
getCount() {
return parseInt(this._temp?.count || 0);
},

/**
* Refresh data continuously.
*
* @param {callback} callback
* @param {number} timeout
*/
refresh(callback, timeout) {
this._temp.lastRefreshed = Date.now();

this.request().then(() => {
const now = Date.now();

callback.apply(this);

const timeoutDiff = now - this._temp.lastRefreshed;

// If request took longer than timeout, run next refresh instantly.
if (timeout && timeoutDiff >= timeout) {
this.refresh(callback, timeout);
}

// Request was quicker than timeout, queue next refresh call.
else {
setTimeout(() => {
this.refresh(callback, timeout);
}, timeout - timeoutDiff);
}
});
}
};

// Initiate refresh loop
VisitorCounter.refresh(function() {
$('#customer_count span').text(VisitorCounter.getCount());
}, 2000);

})(jQuery);

Next add the below to your themes functions.php file...

/functions.php

class VisitorCounter {

private static $instance;

/**
* @var string $file Relative path to the tracking file.
*/

public $file = 'users/';

/**
* @var int $expires Automatically expire vistor after X amount of seconds.
*/

public $expires = 3;

/**
* @return $this
*/
public static function init() {
if ( !static::$instance ) {
static::$instance = new static( ...func_get_args() );
}

return static::$instance;
}

/**
* Get the full database file path and create file if not exists.
*
* @return string|false
*/
public function getPath() {

$post_id = $_GET['post_id'];
$path = get_stylesheet_directory() . '/' . ltrim( $this->file, '/' ) . 'product-view-id-' . $post_id . '.db';
$exists = file_exists( $path );

if ( !$exists ) {
wp_mkdir_p( dirname( $path ) );
$exists = touch( $path );
}
return $exists ? $path : true;
}
/**
* Read the contents of the visitors database file as a JSON.
*
* @return array
*/
public function getData() {
if ( $path = $this->getPath() ) {
if ( $contents = file_get_contents( $path ) ) {
if ( $json = @json_decode( $contents, true ) ) {
return $this->cleanData( $json );
}
}
}

return [];
}

/**
* Clean the visitor data by removing expired entries.
*
* @param array $input
* @return array
*/
private function cleanData( array $input ) {
$now = time();

foreach ( $input as $ip => $timestamp ) {
if ( $timestamp + $this->expires < $now ) {
unset( $input[ $ip ] );
}
}

return $input;
}

/**
* Add visitor count data.
*
* @param string $ip
* @param int $timestamp
* @return array
*/
public function logUser() {

// Get current data.
$data = $this->getData();

// Add new entry.
if ( $ip = $this->getUserIp() ) {
$data[ $ip ] = time();
}

// Clean data before saving.
$data = $this->cleanData( $data );

// Encode and save data.
file_put_contents( $this->getPath(), wp_json_encode( $data ) );

// Return data.
return $data;
}

/**
* Get the current users IP address.
*
* @return string|null
*/
public function getUserIp() {

// In order of preference, with the best ones for this purpose first.
$address_headers = [
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
];

$client_ip = null;

foreach ( $address_headers as $header ) {
if ( !empty( $_SERVER[ $header ] ) ) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$address_chain = explode( ',', $_SERVER[ $header ] );
$client_ip = trim( $address_chain[ 0 ] );
break;
}
}

return $client_ip;
}
}

/**
* Helper function for visitor counter class.
*
* @return VisitorCounter
*/
function visitor_counter() {
return VisitorCounter::init();
}

/**
* Register an ajax request handler.
*/
add_action( 'wp_ajax_active_visitor', 'handle_visitor_activity' );
add_action( 'wp_ajax_nopriv_active_visitor', 'handle_visitor_activity' );
function handle_visitor_activity() {
$controller = visitor_counter();
$controller->logUser();
wp_send_json_success( count( $controller->getData() ) );
}

/**
* Load our javascript file on the frontend data.
*/
add_action( 'wp_enqueue_scripts', function() {
if ( is_product()) {
// Load the counter javascript file after `jquery` in the footer.
wp_enqueue_script( 'visitor-counter', get_stylesheet_directory_uri() . '/js/visitor-counter.js', [ 'jquery' ], '1.0.0', true );

// Load php data that can be accessed in javascript.
wp_localize_script( 'visitor-counter', 'VisitorCounterVars', [
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
'ajaxAction' => 'active_visitor',
'post_id'=> get_the_id()
] );
}
} );

Things to lookup...

WordPress ajax handlers (add_action( 'wp_ajax_' ) and add_action( 'wp_ajax_nopriv_' )) documentation can be found here:

  • https://developer.wordpress.org/plugins/javascript/ajax/
  • https://developer.wordpress.org/reference/hooks/wp_ajax_action/
  • https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/

WordPress JSON responses wp_send_json_error() and wp_send_json_success():

  • https://developer.wordpress.org/reference/functions/wp_send_json_error/
  • https://developer.wordpress.org/reference/functions/wp_send_json_success/

Loading javascript on the frontend:

  • https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
  • https://developer.wordpress.org/reference/functions/wp_enqueue_script/
  • https://developer.wordpress.org/reference/functions/wp_localize_script/

Javascript JSON parsing error: Unexpected token ' in JSON at position 1

Finally, Got the solution

var timeSlots = "['11AM-12PM', '1PM-2PM']";
timeSlots.replace(/'/g, '"');
console.log(JSON.parse(timeSlots));

SyntaxError: Unexpected token = in JSON at position 11 at JSON.parse (anonymous)

The request you are sending is not valid. You have used = in json. It should be colan (:):
Please replace this to:

{
"title" : "new title"
}

Hope it will work!



Related Topics



Leave a reply



Submit