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

Exploring html select and input elements in a loop

Currently, I am in the process of developing an application that calculates the total price of selected items based on user input. Each row consists of two dropdown menus (ID/item) and a quantity input field. Additionally, users have the option to add rows ...

Can you provide me with the URL for the jQuery post function?

Could someone please clarify which URL I should use in the $.post call to the server for a node.js file? Most tutorials demonstrate with PHP files, but I'm unsure about calling node.js files. Should I post it to the app.js file or the route file? Thi ...

I'm perplexed as to why my JavaScript code isn't successfully adding data to my database

Recently, I delved into the world of NodeJS and Express. My goal was to utilize Node and Express along with MongoDB to establish a server and APIs for adding data to the database. Specifically, I aimed to write the code in ESmodules syntax for JavaScript. ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

Error in .NET when deserializing a missing member

There's a library I'm using with a custom exception, but I've encountered an issue. The custom exception code is as follows: public class CustomException : Exception { public CustomException(string message) : base(message) { } } ...

Is there a way to prevent this picture from shifting?

I am currently revamping the content on my work website using Joomla. I have received the old copy and now I need to enhance it. The website in question is 24x7cloud.co.uk. At the bottom of the page, I aim to include an "Accreditation's" section. Howe ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Is there a way to accomplish this without using settimeout?

Whenever the Like button is pressed, I want to trigger the loading process I expect to see LOAD_POST_SUCCESS immediately after LIKE_POST_SUCCESS Pressing the Like button should initiate the load process After LIKE_POST_SUCESS, I want to see LOAD_POST_SU ...

Creating distinctive identifiers for individual function parameters in JavaScript using addEventListener

I am working on a for loop that dynamically generates elements within a div. Each element should trigger the same function, but with a unique ID. for(var i = 0; i < 10; i++) { var p = document.createElement("p"); var t = document. ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

Trouble with displaying canvas images in imageDraw() function

I'm having trouble with my Imagedraw() method when trying to obtain image data using toDataURL(). var video = document.getElementById('media-video'); var videoCurrentTime = document.getElementById('media-video').currentTime; var ...

Display additional javascript code for expanding a marquee

Currently, I am working on a stock ticker project using JavaScript. It's progressing well, and now I am focusing on adding a "show more" button to style the ticker. The button should be placed outside of the marquee. When clicked, it will expand the m ...

When incorporating sequelize's belongsTo and hasOne methods, you may encounter an issue where the call stack size surpass

Within my Discussion entity, I have: Discussion.hasOne(sequelize.import('./sound'), { relations: false }) While in the Sound entity, the relationship is defined as: Sound.belongsTo(sequelize.import('./discussion')) To load t ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

Is it possible to animate multiple SVGs on a webpage with just the click of a button?

Is there a way to trigger the animation in the SVG each time a next/prev button is clicked while navigating through a carousel where the same SVG is repeated multiple times? The carousel is built using PHP and a while loop. jQuery(document).ready(function ...

Error in Jquery Ajax due to an unexpected token ':' being caught

My spring MVC application is experiencing an issue when using jQuery AJAX to send data to the server from my HTML page. The error message indicates a problem with dataType: 'json', specifically pointing out the unexpected symbol :. $(document).r ...

Separate the elements with a delimiter

I am in the process of inserting various links into a division by iterating through a group of other elements. The script appears to be as follows $('.js-section').children().each(function() { var initial = $(this).data('initial'); ...

Emulating a mouse click in jQuery/JavaScript on a webpage link

I am seeking a way to programmatically trigger a click on any link within a webpage using JavaScript. The challenge lies in ensuring that if the link has an 'onclick' event bound to it by another unknown JavaScript function, that event is trigger ...

JQuery is having issues with $(this) and the find function not working properly

I am attempting to access a child of the div with the class form-group, specifically, I want to display the value of the input element. <div class="form-group"> <label>text</label> <input name="text" type="text" class="form-co ...

A guide on verifying a username and password via URL using JavaScript

As I work on developing a hybrid application using the Intel XDK tool and jQuery Mobile framework for the user interface, one of my current tasks is implementing a login function. This function involves simply inputting a username and password and clicking ...