Error found: Unexpected character in JSON data at line 1, position 4

Here is a json encoded string:

{
    "user": [{
        "id": "45",
        "name": "Raj",
        "loc": "kizhakood",
        "dist": "wayanad",
        "phone": "9815678421",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3c2f243d2f262f202d2f0e29232f2722602d">[email protected]</a>",
        "gender": "male",
        "proofid": "2",
        "sslc": "SSLC",
        "plus2": "PLUS 2",
        "degree": "DEGREE",
        "pg": ""
    }]
}

When attempting to JSON.parse(responcetext), an error occurs:

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

This code snippet includes JavaScript functionality:

<script type="application/javascript">
        function loadup(str){

        var xmlhttp;
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        var jsontext = xmlhttp.responseText;

        document.getElementById("mydiv").innerHTML=jsontext;

        var userobj=JSON.parse(jsontext);
        document.getElementById("myd").innerHTML=userobj.user[0].name;

    }
        } 

        xmlhttp.open("GET","plain.php?edit="+str,true);
        xmlhttp.send();
        }

    </script>

The PHP file that generates the JSON response:

<?php
   include"connection.php";
    $id = $_GET['edit'];
    $sql = "SELECT * FROM form WHERE id=$id";
    $result = $conn->query($sql);

    $row=$result->fetch_assoc();
     $json_res=array();
    $json_res = array('user'=>array($row));





    echo json_encode($json_res);


    $conn->close();
?>

Answer №1

If you already have valid json data, you can easily access attributes using the following method

var jsonData = '{"profile":[{"id":"123","username":"JohnDoe","location":"New York","email":"john.doe@example.com"}]}';

var parsedData = JSON.parse(jsonData);

alert(parsedData.profile[0].id);
alert(parsedData.profile[0].username);
alert(parsedData.profile[0].email);

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

Transform JavaScript variables into CSS variables

Similar Post: Avoiding repeated constants in CSS I am currently working on a javascript file that aims to adjust my site's resolution based on the width and height of the viewport. While I have successfully retrieved these values using JavaScript ...

I'm looking to display 9 images on a single page that rotate every 5 seconds between 3 different images. While I can figure out how to display one image easily, I'm

<script type="text/javascript"> var currPic = 1; var totPics = 9; var keepTime; function setupPicChange() { keepTime = setTimeout("changePic()", 5000); } function changePic() { currPic++; if (currPic > totPics) currPic = 1; var f ...

Vue.js is unable to reach a component's method

I have two Vue.js components Lobby and Game. My goal is to utilize Game as a model that holds all the necessary logic for creating a game, which can then be triggered through interactions in the Lobby component. Whenever I try to run the application and c ...

What is the process through which Generator.next() works with its parameter?

According to the documentation, it mentions that "You can also provide a parameter to the next method to send a value to the generator." But where exactly does it send this value to? Let's consider these 3 different generator functions: function* fi ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Error: The function coolArr.printArray is not defined in the npm package being imported

My custom package contains an index.js file with the following code: module.exports = class CoolArray extends Array { printArray() { console.log(this); } } After transpiling the code using es2015 syntax with Babel, I connected the package to my te ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

Encountered a JSON parsing error: Expected the beginning of an array but instead found the beginning of an object at line 1

I'm struggling with the code and need some assistance. I've hit a roadblock and can't figure out what else needs to be done. After trying multiple approaches, I am still unsure about the next steps. My focus is on retrieving data from the & ...

Develop a data structure that resembles a map

I am currently working with a product model that looks like this: export class Product { id: number; name: string; price: number; url: string; description: string; constructor() { this.id = 1; this.name = '&apo ...

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

Utilizing the Value of an Array as a Key in a Different Array

Can someone help me with reading data from two arrays? The first array looks like this: tnails: [ { mil: '/static/mini/t-icon-mil.png', mar: '/static/mini/t-icon-mar.png', brd: '/static/mini/t-icon-brd.png&ap ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

What is the most effective way to use Ajax to send a Model to a controller without the need for a

I have a view that consists of a list of partial views. <script src="~/Scripts/SortProducts.js" type="text/javascript"></script> @using System.Collections.Generic; @using OnlineShop.Models; @model List<Product> ...

Creating a personalized error handling system for a node API is something that piques my interest

I am looking to implement custom error handling for specific error codes in order to easily respond with predefined necessary information. I could use some guidance as I am unsure of how to proceed with this feature. The code snippet would appear as follo ...

Separate and move the data into an array within the migration script

const cArray = [ { CompanyCd: 'Yello', CompanyName: "Yello & Productions", }, { CompanyCd: 'Orange & proce', CompanyName: "Orange & proce c/o", }, { CompanyCd: 'Lamus & FAMOUS', ...

Making an asynchronous call from Index.html to PHP Script

I am currently working on implementing an AJAX call to my PHP Script. While I can successfully echo the results from my data.php file, I am now facing a challenge regarding how to initiate the call from index.html in order to retrieve the table results s ...

Restricting href Usage Based on Session

I find myself in a challenging situation without a clear solution at hand. Within this code, I am utilizing a link and a button for which I need to save the page in a database. Therefore, creating a server control is not an option as it will not be render ...

ADVENTURE BLOCKED - Intercept error: net::ERR_BLOCKED_BY_CLIENT

I've encountered an issue where my initialize function doesn't run properly when a user has an ad blocker enabled. It seems that the ads-script.js file is being blocked by the client with a net::ERR_BLOCKED_BY_CLIENT error, leading to my .done ca ...

Notification fails to display following POST request

Whenever the select menu displays "Please select your country" and I click the checkout button, an alert pops up. But if I select Canada, then go back to selecting "Please select your country" and press checkout, no alert appears. I need the alert to alway ...

Iterating through the sorted list in reverse order, retrieving the text of each list item

Is there a way to navigate through an ordered list, extract and return the text based on a scenario where the user clicks on an li element like Cat 1-2? The goal is to concatenate all parent li's text into either a string or an array. If an array is u ...