What steps can be taken to resolve the error message: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data?

I'm facing an issue while trying to retrieve data for my map using an AJAX call. The error message I receive is:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
. Interestingly, two previous datasets in my application worked fine and were displayed on the screen. However, when I attempted to add a third dataset, this error occurred and the variable dataArray remains empty.

geojson_popupInfo = {
    "type": "FeatureCollection",
    "features": [],
};

geojson_dataTable = {
    "type": "FeatureCollection",
    "features": [],
};

var dataArray = data.split(", ;");
dataArray.pop();

dataArray.forEach(function(d){
d = d.split(", "); 

var feature_popupInfo = {
    "type": "Feature",
    "properties": {}, 
    "geometry": JSON.parse(d[fieldList.length]) 
};

var feature_dataTable = {
    "type": "Feature",
    "properties": {}, 
    "geometry": JSON.parse(d[fieldList.length]) 
};

for (var i=0; i<fieldList.length; i++){
    if ([fieldList[i].show_field] == 't') {
        feature_popupInfo.properties[fieldList[i].field_alias] = d[i];
    }
    feature_dataTable.properties[fieldList[i].field_name] = d[i]; 
};
geojson_popupInfo.features.push(feature_popupInfo);
geojson_dataTable.features.push(feature_dataTable);
});
console.log(dataArray)

Answer №1

Ensure that your PHP script is strictly outputting JSON data. At the moment, you are currently:

echo $attr.", ";

Later on, you have:

echo json_encode($attribute_names);

This means your output includes both comma-separated text:

2, 1, 0, 0, 0, , 0, 0, [snip], 0, 1840, 0, 2,

as well as valid GeoJSON:

{"type":"MultiPolygon","coordinates":[[[[6.74578464881977, [snip] ,53.3291017450563]]]]}

Only return GeoJSON with a single echo, and avoid any other unnecessary echo calls to resolve this issue.

Answer №2

It looks like the issue here is that the output from your script contains a combination of JSON and non-JSON data, resulting in portions of the JSON being split up when processed by JavaScript. This causes your array d to no longer be valid JSON.

In most cases, returning pure JSON would be ideal. However, due to the JSON data within the table, achieving this can be challenging.

There are a couple of approaches you could take:

  1. Decode the JSON data when extracting it from the table, convert it into an array of objects, re-encode the entire array as JSON, and then return it.
  2. Alternatively, instead of using commas and semicolons to separate your data, consider using unique characters or strings like '|' or 'XYZ' that have no significance in JSON and aren't present in the database values.

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

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

Unable to create a pie chart with chartjs using JSON data

I am having trouble creating a pie chart using canvas.JS. I have already tried iterating through them in a loop. The JSON data returned looks like this: [[{"label":"belum","x":1},{"label":"sudah","x":5}]] Below is the code I am using to retrieve the JS ...

Is it possible for the JavaScript code to cease execution once the tab is closed?

I am working on a JavaScript code snippet that is designed to execute once a component finishes loading: function HelloThere() { React.useEffect(() => { setTimeout(() => { // code to make a server call to write data to DB ...

Learn how to dynamically switch the background image of a webpage using a button in AngularJS

Hey there, I'm currently working on incorporating interactive buttons into my website to give users the ability to customize the background. I've been experimenting with Angular to achieve this feature. So far, I've managed to change the ba ...

Looking for a way to utilize a Devise user account in an unconfirmed or locked state for AJAX interactions?

Currently, I am attempting to integrate the devise views utilizing JS to manage the responses. While I aim to utilize the default devise error messages, I am facing difficulty in isolating individual types of errors such as unconfirmed or locked accounts d ...

Learn the process of adding asynchronous middleware modules to your express.js application

I'm currently developing an express application that utilizes the node_acl module along with a MongoDB database. I have created a custom module that sets up and configures node_acl asynchronously. This middleware needs to be called as the second piece ...

ruby use JSON library to import data

How can I utilize the parsed information from the data.rb file within the main.rb file? I am attempting to determine the frequency of the years "2017" and "2014". I aim to send back both counts to the count_years method found in main.rb. What is the corr ...

The significance of passing attributes in Webgl2

I'm currently learning about three.js and working my way through the documentation. I'm struggling to understand the meaning behind the following explanation, could someone provide some assistance? When you manually create the WebGL 2 renderin ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Fullcalendar feature that restricts users from selecting multiple days for an event

I am using the fullcalendar plugin from http://fullcalendar.io/ and I want to restrict users from creating events spanning multiple days. $('#calendar').fullCalendar({ defaultView: 'agendaWeek', lang: "fr", header: ...

What is the best way to dynamically set the number of text views in a horizontal scroll view as data is being fetched from JSON parsing

My application fetches JSON data from a URL and then displays it within a text view that is located inside a horizontal scroll view. JSONArray ja = response.getJSONArray("results"); ArrayList<Details> myModelLis ...

React State Update Triggered by Changing Hidden Input/Textarea Value - No User Input Required

To activate a function when the contents of a hidden input, textarea, or textfield change in React without requiring user input to trigger it, you will need to dynamically adjust the value of the hidden input and then have the function automatically exec ...

Tips for sending an icon as a prop in React components

I'm struggling to implement an icon as a prop while using props for "optionText" and "optionIcon". The optionText is working fine, but I'm facing issues with the OptionIcon. File where I'm creating props import Icon from ...

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

What is the reason behind the absence of the C++ syntax for a string loop in javascript?

UPDATE: At first, I believed that the following syntax was not functioning due to a mistake in my code and the fact that I have not encountered it being utilized in Javascript before. My primary concern lies in why this particular syntax is not more preval ...

Ember.js alternative for Angular's filter for searching through ng-models

Looking for an easy way to implement a search filter similar to Angular? <input type="text" ng-model="resultFilter" placeholder="Search"> <ul> <li ng-repeat="result in results | filter:resultFilter">{{result.name}}</li> </u ...

Creating an HTML table from dynamic JSON data - A comprehensive guide

I am in need of a solution to transform JSON data into an HTML table format quickly and easily. Can anyone provide guidance on effectively utilizing PartialView to recursively render tables, ensuring that most details are visible? ...

How to extract attributes from a PHP object using JSON?

I am just starting out with PHP programming and I'm working on extracting information from a JSON string using PHP. Here is the code snippet I have used: $json = file_get_contents('data.json') var_dump(json_decode($json)); to better unders ...

Malfunction detected in Json autocomplete function

Currently, I am working on implementing an auto-complete search feature using data from my database. The PHP code below creates an array for this purpose: $leaders= mysql_query("SELECT model_name,model_id FROM models ORDER by model_name D ...