Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dexter_siah's avatar

JSON.parse error

I'm trying to use the fetch api to get my data through the controller but I'm getting an error

SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

The current route that is fetching the data is /report/{report} and im fetching the data from fetchMap.

JavaScript

function getId(){
    const report = document.querySelector("#reportId");
    const reportId = report.dataset.id;
    const route = `fetchMap?id=${reportId}`;

    fetchLngLat(route);
}

function fetchLngLat(route){

    fetch(route)
        .then(res => res.json())
        .then(data => {
           console.log(data);
        })
        .catch(err => console.log(err));
}

ReportController

public function fetchMap(Request $request){
    $report = Report::find($request->id);

    return response()->json($report);
}

Route

Route::get('fetchMap','ReportController@fetchMap');

I have tried to dd in the fetchMap method and it does return my report when i enter the url /fetchMap?id=1 but somehow it is getting a parse error in my js script.

Any help would be appreciated

0 likes
3 replies
Tray2's avatar

Open the developer tools in your browser and take a look at the response you get from the server.

It's most likely not properly formed JSON. So the web api you are hitting does not function properly.

Nakov's avatar

@dexter_siah I believe that this is the line that causes the error for you:

.then(res => res.json())

Try just logging out the response and see.

dexter_siah's avatar
dexter_siah
OP
Best Answer
Level 1

Got it thanks @nakov and @tray2 . Apparently the route that was passed was report/{report}/fetchMap?id=1 instead of fetchMap?id=1. So i just changed this.

const route = `/fetchMap?id=${reportId}`;  //Added forward slash

Please or to participate in this conversation.