issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'...

However, when I comment out the line where eval() is used and instead use document.write(data), the string appears...

Here is the code snippet:

<html>
<head>
    <script type='text/javascript' src='jquery.js'></script>
    <script type='text/javascript'>

    var go = function() {

        $.get("testjson.php", function(data) {

            var obj = eval("(" + data + ")");

            document.write(obj.name + "<br />");
            document.write(obj.date + "<br />");
        });
    }
    </script>
</head>
<body>
    <input type='button' value='go' onclick='go()' />
<body>
</html>

And here is the code of my testjson.php file:

<?php

    $msg = array(
        "name"=>"hi there Victor!",
        "date"=>"Monday 21st Feb 2010"
    );

    $myMsg = json_encode($msg);

    echo $myMsg;

?>

I am using the latest version of jQuery.

Answer №1

While there may be additional recommendations provided in the feedback and responses regarding utilizing $.getJSON() over eval(), or indicating json as an argument within $.get(), these are all valid suggestions. However, the root cause of the issue lies elsewhere.

Essentially, a simple oversight is present in your var go = .... function definition, where a semi-colon is absent following the closing brace towards the end.

Answer №2

Finally, the issue has been resolved! It's quite surprising how simply removing some commented HTML code under my PHP code fixed everything. Who would have thought a comment could affect the functionality of the code? Technology can be so unpredictable at times.

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

Install the npm package if there have been modifications to the package.json file

In short: Can we make npm install run automatically before executing any npm script if the package.json file has been modified? Situation Summary Imagine you switch to a branch that has updated the package.json file. You try running npm run my-script, bu ...

Sharing stickers with Discord.js version 13

I have encountered an issue while trying to forward messages sent to my bot via DM. Everything is functioning smoothly, except for sending stickers. Whenever I attempt to send a message with a sticker, an Error DiscordAPIError: Cannot use this sticker is ...

Exploring ways to retrieve the parent property name within System.Text.Json.Serialization.JsonConverter

Working with a 3rd Party API that provides data in the following format: { "dynamicFields": { "prop1": "val1", "prop2": "val2", "prop3": "val3" }, // otherFields ... } ...

Is there a solution to rectify the error related to POST net::ERR_CONNECTION_REFUSED?

Every time I try to post via ajax, an error keeps popping up. Here are the snippets of my code: let xhr = new XMLHttpRequest() let data ={ "name": "test", "phone": "12345678", "email": &qu ...

TypeScript - Indexable Type

Here is an explanation of some interesting syntax examples: interface StringArray { [index: number]: string; } This code snippet defines a type called StringArray, specifying that when the array is indexed with a number, it will return a string. For e ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Is there a way to transform a .pcm file to a wav file using node.js?

I'm working on a project that generates a pcm file from a stream and saves it after the stream finishes. Now, I am looking for a way to convert this .pcm file to a .wav or another audio format using an npm package. Can anyone suggest a solution or poi ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

Avoid loading the background image by utilizing CSS to set the background image

Whenever I attempt to assign a background image using CSS, it triggers a console error. This is my CSS code: body { background-image: url("background.png"); background-repeat: no-repeat; } The error message displayed is: GET http://localhost/myWeb/ ...

Utilize dynamically generated Java Strings to assign JSON values for effective Karate integration testing in a dynamic manner

For my Karate Integration testing, I am looking to set randomString/randomNumber as Json values instead of hardcoded ones for the payload using the PUT HTTP verb. Additionally, I would like to store these JSON values in a database. ...

Tips for dynamically passing a URL to a function using the onload event

I require assistance with passing a dynamic URL to a function. code onload="getImage('+ val.logo +');" onclick="loadPageMerchantInfo('+ val.merchant_id +'); The value of val.logo contains a URL such as: https://www.example.com/upload ...

Activating the delete event trigger for a tinyMCE object

How can I create a function that activates when a user deletes an object in tinyMCE? I want to remove uploaded images from a cache folder whenever a user deletes an image from the tinyMCE editor. If they upload an image and then delete it, I would like an ...

Gather a combination of key-value pairs from JSONArrays in Java and consolidate them into a single JSONArray

I am working on a task involving JSONObject, with two JSONArray to extract key and value pairs and return them as a new JSONArray: The first JSONArray contains two objects shown below: [{"name": "John", "id": "1"}, ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

Is it better to conceal modals or completely eliminate them from the DOM when working with React?

I am currently developing a React application that involves multiple modals, with only one active at a time and no nested modals. I am torn between two approaches for handling the showing and hiding of these modals: The first approach involves having a b ...

Change the background of the play/stop icon with a jquery toggle

There is a list of video links with play icons as backgrounds in front of them. When a user clicks on a link, the video will start playing in a player located to the left of the links. The clicked link's background icon changes to a 'stop' i ...

Leverage Angular's constant feature in scenarios that extend beyond the

Even though it may not be recommended, I find it fascinating to use Angular services outside of the angular framework. One example is having .constant('APIprefix','/api') I am curious about how to access the value of APIprefix outside ...

Obtaining a 16-bit integer from the response of an LWIP server

On the server side, I have implemented a loop that takes a 16-bit integer ranging from 0 to 639 and splits it into two 8-bit characters to populate a buffer of 1280 Bytes. The buffer is then sent via TCP-IP to the client. .c unsigned int data2[1000]; ch ...

How do I determine the data type present in the response from the graph API?

As a beginner in graph API, I find myself needing to use multiple graph APIs simultaneously within my application. One question that arises is how can I determine the data type of the response? Specifically, how do I identify if the response contains frie ...

Data streaming using Node.js

Is it feasible to continuously stream data from the server to the client using Node.js? My goal is to send a single AJAX request to Node.js, establish a persistent connection, and stream data to the client for real-time updates on the page. Latest Update: ...