Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token

Take a look at my PHP snippet:

$infoJson = array('info' => array());
while($row = mysqli_fetch_array($query))
{
    array_push($infoJson['info'],
    [
        'section' => $row['section'],
        'source' => $row['source'],
        'project' => $row['project'],
        'client' => $row['client'],
        'date' => $row['date'],
        'id' => $row['id']
    ]);
}
echo json_encode($infoJson);

Now check out the Javascript code:

request = new XMLHttpRequest();
request.onreadystatechange = function()
{
    if(request.readyState == 4 && request.status == 200)
    {
        var response = request.responseText;
        response = JSON.parse(response);
    }
}
request.open('GET','http:edit.php?requestedArray=printArray',true);
request.send();

Here's what the PHP prints out:

{"info":[{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/7\/7a\/SNES-Controller.jpg\/1280px-SNES-Controller.jpg","project":"SNES","client":"Nintendo","date":"1990","id":"7"},{"section":"printArray","source":"http:\/\/ecx.images-amazon.com\/images\/I\/81Q0l1t%2BaJL._SL1500_.jpg","project":"Playstation","client":"Sony","date":"1994","id":"8"},{"section":"printArray","source":"http:\/\/upload.wikimedia.org\/wikipedia\/commons\/e\/ed\/Xbox-360-S-Controller.png","project":"Xbox 360","client":"Microsoft","date":"2005","id":"9"}]}

If I skip using JSON.parse and simply log the response, it does come through as a string.

Answer №1

Your code works perfectly, but there seems to be an issue with the obscure character '\ufeff' that appears at the start of the string. This character is known as the UTF-16 byte order mark. It's likely that the problem lies in the incorrect or missing charset specified in your Content-Type header.

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

Is the oscillator value remaining stagnant in Safari?

Is there a way to utilize the web audio API alongside NexusUI JS for dial/knobs? When I use Chrome, the dial changes the oscillator frequency, but in Safari, it seems to be playing the default 440hz. Can anyone guide me on what could be the issue or what ...

Tips for crafting a secure SQLite query to prevent injection vulnerabilities

I'm struggling to verify if 'myusername' and 'mypassword' exist in the database, and I need help displaying the results when there's a match. The code I've written doesn't seem to be returning or displaying any resul ...

Transform JSON data into a JavaScript variable

Just diving into the world of Node.js and JavaScript. Please forgive me if my question seems basic. Here is a snippet of my Node.js code that retrieves data from MySQL: var quer = connection.query('select password from users where mail="' ...

ASP.NET AJAX 2.0/3.5 HTML editing tool

Is it possible to use the HTML editor in ASP.NET Ajax 2.0/3.5 to read an RTF file from a directory? If so, how can I accomplish this? Please provide guidance. ...

I'm having trouble navigating in react-router 4, the route keeps redirect

Can someone help me figure out why all the links are redirecting to a blank page? The dependencies I'm using are: "react-router": "^4.2.0", "react-router-dom": "^4.1.1", App.js import { BrowserRouter, Route, Switch } from 'react-router-dom&ap ...

Identifying the JS Tree nodes that have been repositioned via drag-and-drop

I'm working with a JS Tree structure that includes drag and drop functionality. Here's the basic code I have so far: $('#using_html_1').jstree({ "core": { "check_callback":true }, "plugins" : ["dn ...

Optimal method for linking NodeJS and Angular in a seamless integration

I am currently working on developing a web application that integrates a Node server as the backend and Angular for the front end. At the moment, my application consists of two JavaScript files: server.js and controller.js. Below is the code snippet for ea ...

How can we make sure the selected tab opens in jQuery tabbed content?

I'm trying to make my tabbed content open on a specific tab by changing the URL. I remember seeing something like this before but can't seem to find it! Here's the fiddle I created: http://jsfiddle.net/sW966/ Currently, the default tab is ...

In search of a web hosting provider offering a variety of technologies such as ColdFusion, PHP, MS SQL Server, and MySQL for maximum

Is it feasible to set up a web server that supports the following technologies: ColdFusion, PHP, MS SQL Server, and MySQL? I'm uncertain because my web developer claims they all need to be utilized, but I'm not convinced. Any guidance or explan ...

challenge with PHP regular expressions

I am trying to extract the <form> from a website. However, there is a lot of other HTML code in between the form tags. Is there a way to remove everything else and just keep the form part using PHP? $str = file_get_contents('http://bingphp.code ...

The JSON retrieved from the API contains additional characters

Currently, I am dealing with an API that is quite old and unfortunately lacks sufficient documentation. Upon making a GET request on a specific route, the response returns JSON data along with additional characters at the beginning. This unexpected sequen ...

The printer is malfunctioning

My webpage has a div that includes various input fields with values assigned using jQuery. I wanted to print the contents of this div, so I found some code online to help me achieve this. However, when I try to print, the values in the input fields end up ...

using ajax to fetch a file from laravel

My goal is to download a file by sending necessary parameters through an ajax request. In the process, I saved the output file in the public/exports directory and attempted to redirect to that file path in the success callback. public function downloadRe ...

Reactively created menu using JQuery

Looking to implement a dynamic JQuery menu using React (ES6). Utilizing the JQuery menu examples (https://jqueryui.com/menu/) as a guide, however, those examples only cover static menus. It doesn't clarify how to modify menu items like updating labels ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

steps to adjust screen zoom back to default after automatic zoom in forms

I'm not very well-versed in javascript/jquery and have been on an extensive search for a solution to my specific problem. While I've come across some close answers, I am struggling to adapt them to fit my own scenario. On my website, I have a fo ...

What is the best way to automatically set today's date as the default in a datepicker using jQuery

Currently utilizing the jQuery datepicker from (http://keith-wood.name/datepick.html), I am seeking to customize the calendar to display a specific date that I select as today's date, rather than automatically defaulting to the system date. Is there a ...

A method in JavaScript to fetch a single variable using the GET request

Although I am new to writing JavaScript, I am currently working on an iOS application that will make use of JavaScriptCore's framework to interpret a piece of javascript code in order to obtain a specific variable. My goal is to establish a GET reques ...

Why won't my controller function fire with ng-click in AngularJS?

I'm having trouble getting a function to execute when my button is clicked. Despite the fact that this code appears correct, the function defined in my controller isn't being triggered. The code compiles without errors as shown in the console. A ...

Unable to establish connection between PHP and Postgres DB on CentOS 6.5

I have set up a CentOS 6.5 virtual machine on VirtualBox with Apache, PHP, PHP Postgres extension (php-pgsql) and Postgres database configured. I made changes to the pg_hba.conf file to allow connections: # "local" is for Unix domain socket connections on ...