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

Is it worth considering refactoring RoleInterface to simply Role right now?

After upgrading to Symfony 3.3, I came across a deprecation warning mentioning that RoleInterface is deprecated and advising to extend a Role class instead. Upon reading some of the discussions on this topic on GitHub, it appears that both options will be ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

Incorporate a class into a link within the wp_list_pages function

I've been experimenting with creating a hover effect on list items using the wp_list_pages() function in my Wordpress theme. Despite my efforts, I've hit a roadblock in getting the hover effect to work properly. As a beginner in web development, ...

Is it possible to continuously update a Google line chart by programmatically adding rows at specific intervals using an AJAX call

Is there a way to dynamically add rows to the Google line chart each time data is retrieved via an AJAX call at set intervals? This is the existing code: google.charts.load('current', {'packages':['line']}); google.charts. ...

The presence of Bootstrap remains hidden unless space is designated for it

Question about Bootstrap 5.1.3: Is there a way to hide elements on a page using the bootstrap class ".invisible" without allocating space for them? Currently, when the elements are set to visible using the class ".visible", they occupy space on the page ...

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

Integrating chat functionality with a structured data format

Considering creating a collaborative communication platform, I am contemplating whether to develop a comprehensive application in JavaScript with MVC architecture or utilize it solely for managing message delivery using Node.js and socketIO. Would it be m ...

Compare two dictionaries in a Pythonic manner and add nested objects to one dictionary if the keys match

As a Python newcomer, I have some working code but am interested in exploring if there is a more efficient approach to solving this problem. The task at hand involves processing two dictionaries in Python: one containing details about volumes and the othe ...

What is the reason for the removal of escape characters by WebView's evaluateJavascript() method

I am facing an issue with passing a stringified JSON object into my WebView as a string. The problem arises when the JSON contains another nested JSON object. JSONObject object = new JSONObject; object.put("key1", "val1"); object.put("key2", "val2"); Stri ...

Update the field 'payments._id' in MongoDB to a timestamp

I need to change the value of 'payments._id' to a timestamp. In MongoDB, the 'payments._id' object is automatically generated when inserting a document into the collection. onMounted(async () => { const res = await axios.get(" ...

Set the display property of all child elements within the DIV to none

CSS <div class="container"> <span></span> <input type="text"> </div> JavaScript function hideElements(){ let container = document.querySelector(".container"); let elements = ...

What is the best way to upload my React project to GitHub without adding the node modules directory?

I'm looking to share my React Project on GitHub, but I don't want to include the node modules folder. What's the best way to go about this? ...

Employing ng-repeat within a ui-scope

I'm having trouble getting my ui-view to update dynamically using ng-repeat. I'm not sure if what I want to do is even possible because when I add static objects to intro.html, they display properly. Thank you for any assistance, JS }).st ...

Managing Modules at Runtime in Electron and Typescript: Best Practices to Ensure Smooth Operation

Creating an Electron application using Typescript has led to a specific project structure upon compilation: dist html index.html scripts ApplicationView.js ApplicationViewModel.js The index.html file includes the following script tag: <script ...

Guide to creating a nested list using the jQuery :header selector

Here is the structure of my html: <h1 id="header1">H1</h1> <p>Lorem ipsum</p> <h2 id="header2">H2</h2> <p>lorem ipsum</p> <h2 id="header3">H2</h2> <p>lorem upsum</p ...

Using a JQuery function to execute when a specific radio button is clicked and also on page load

Just diving into JQuery and ran into a little issue with my function. I'm attempting to tweak it so that it only triggers when a specific radio button is clicked (I thought '#UpdateType input[type="radio"]' would do the trick) and also runs ...

The <Django item> cannot be serialized into JSON format

I am currently working on serializing a queryset and here is the code snippet I have: def render_to_response(self, context, **response_kwargs): return HttpResponse(json.simplejson.dumps(list(self.get_queryset())), mimetype=&quo ...

Executing a javascript function from an ajax-loaded webpage

I have a form where I upload a file using an ajax call that includes an API request. Once the API call is successful, I need to update a table displaying the list of uploaded files. Initially, I attempted calling a JavaScript function within the ajax page, ...

Efficiency Comparison: Storing a substantial mysql output in class variables versus a result array

Hello everyone, I've been thinking about what would be more efficient. Let's say we have a large database table with around 50 columns and a class that manages these columns. The class constructor loads all the fields - and this is where my que ...