Trouble Deciphering JSON Array Using Eval Function

I'm facing an issue with two files in my project - one is a PHP file containing an array that is echoed using json_encode, and the other is a JavaScript file containing various functions for a webpage. One particular function in the JavaScript file is giving me trouble as it appears to be incomplete:

/*
 * Function: selectVictim
 * Called from function laserOn()
 *
 * Selects a random victim from a list of victims
 *
 * @return String: victim
 */
function selectVictim()
{
var params = "url=queenofsheep.com/Sheep/victims.php";
var request = new ajaxRequest();

request.open("POST", "victims.php", true);
request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
request.setRequestHeader("Content-Length", params.length);
request.setRequestHeader("Connection", "close");

request.onreadystatechange = function ()
{
    if (this.readyState == 4)
    {
        if (this.status == 200)
        {
            if (this.responseText != null )
            {
                var vicString = this.responseText;
                var vicArray = eval('"'+vicString+'"');
                //var vicArray = vicString.split(',');
                //var numVic = Math.floor(Math.random() * (vicArray - 1));
                alert(vicArray);
            }
            else alert("Ajax error: No data received");
        }
        else alert("Ajax Error: " + this.statusText);
    }
}

request.send(params);
}

This function is intended to process the array from the PHP file, but it is not functioning as expected. Despite the fact that the value of this.responseText is in JSON format like this:

var jsonArr = 
     ["1","2,","3"]

When the function is activated, nothing happens, and evaluating this.responseText results in "undefined."

I'm struggling to figure out what I am doing wrong here. If necessary, I can provide more code examples or details about the actual array. This problem is really frustrating me.

Answer β„–1

Consider including the symbols "(" and ")" when using the Eval Function. This method has proven to be effective in previous implementations.

var newObj = eval('(' + inputString + ')');

Answer β„–2

Opt for utilizing the request keyword instead of this. The use of this points to the window object.

Note: If the response is exactly var jsonArr=[1, 2, 3];, you may want to consider using eval(vicString+';jsonArr'); if modifying the response text isn't an option.

Executing 'eval("var test=[1,2,3];")' would result in returning undefined. Nonetheless, this method is not recommended when working with JSON structures.

Answer β„–3

To avoid using eval, simply set the content type of the response in the server to "application/json". Additionally, it is recommended to utilize an ajax framework rather than creating your own ajax functions.

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 there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...

I am looking to continuously update the progress bar as the AJAX responses are being received

In order to update the progress bar with every response individually, I encountered an issue where multiple responses were being received at once and only the last one would update the progress bar. Despite trying async:false, the progress bar would only u ...

Attempting to retrieve data from cloud Firestore utilizing keyvalue in Angular

My database stores user information under the 'users' collection. I can access this data using the following code: In my service: users$ = this.afs.collection<Users[]>('users').valueChanges(); In my component: public users = t ...

Verify if the arguments of a Discord bot command are in accordance with the format outlined in the commands configuration

I am looking to create a script that verifies if the arguments given for a command align with what the command expects them to be. For instance; When using the config command, the first argument should be either show, set, or reset Additionally, if se ...

ASP.NET Web API is converting to underscore during serialization

In my ApiController, I have a simple code snippet that looks like this: public Version Get() { var version = new System.Version(1, 1, 0, 0); return version; } When I check the output, it shows two formats: JSON and XML. For JSON: {"_Major":1,"_Mino ...

Tips for executing a script while updating npm version

Can a script be executed during the npm version command, after the release number has been incremented but before the git tag is created and pushed? ...

Creating dynamic elements in JavaScript utilizing Bootstrap cards

Looking for help in integrating Bootstrap cards while dynamically generating elements using JavaScript? I am working on a project where I need to generate a list of restaurant recommendations based on user preferences entered through a form, utilizing the ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Organizing an array of objects within MUI cards based on social media platforms

I'm currently developing an application that showcases athlete data in a grid layout using MUI Grid. The colored borders on the left side of each card are determined by the corresponding social network associated with that athlete. https://i.sstatic. ...

What is the cost associated with using the require() function in an Express.js application?

I have a web application built with Express.js that serves one of my domains. The structure of the app.js file is as follows: var express = require('express'); var app = express(); // and so on… To incorporate one of my custom functions in t ...

Trying to assign a value to a property that is not defined

I'm attempting to initiate the loading and exhibition of a .stl file through three.js by implementing the following code: var stlLoader = new THREE.STLLoader(); stlLoader.load('assets/Cap.stl', function (object){ object.position.y = - 1 ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...

Tips for validating multiple forms on a single page without altering the JavaScript validation structure

My JSP page currently consists of two forms: <body> <form id="1"></form> <form id="2"></form> </body> Only one form is visible at a time when the page is viewed. A JavaScript validation file is used to check the ...

When I refresh the content in a DIV, the ROR code doesn't get executed

Hello, I need some assistance with Ajax. I have tried various solutions to this issue, but none of them seem to work. Whenever I attempt to update the content of a DIV using ROR code, it displays the code itself instead of the desired result. I've tr ...

Extracting Client's True IP Address using PHP API

Utilizing the following api: I am able to retrieve country, city, and real IP address in localhost (127.0.0.1) successfully. However, when I implement this code on my website, it displays the server's address instead of the client's. How can I r ...

What is the best way to have a button activate a file input when onChange in a React application?

Having an input field of file type that doesn't allow changing the value attribute and looks unattractive, I replaced it with a button. Now, I need the button to trigger the input file upon clicking. How can this be achieved in React? Edit: The butto ...

Encountering the "ExpressionChangedAfterItHasBeenCheckedError" in Angular 2

As I try to fill in multiple rows within a table that I've created, the table gets populated successfully. However, an error message pops up: "ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous valu ...

What is the best way to maintain data types of variables within an object sent via ajax?

I'm sending an object via ajax to a PHP script for processing. Here's how I'm doing it: var Obj = {id:1, name:"John", value:12.1}; $.ajax({ url : "myfile.php", type : 'POST', data : Obj, success : ...

Managing data in a database on Discord using JavaScript to automatically delete information once it has expired

Recently, I implemented a premium membership feature for my discord bot. However, I encountered an issue where the membership time starts counting down before the intended start time. To resolve this, I am looking to automatically delete the data from the ...

What could be causing the function to not execute before the rest of the code in the React App?

My lack of expertise may be the reason, but I'm unsure how to address this issue: Here's what I have: A button labeled "Check numbers" <Button fullWidth variant="contained" onClick={this.checkOptOut ...