Pull in data using AJAX and store it in an array. [JavaScript]

I'm in the process of working on an AJAX script that loads a file into an array.

function loadGame() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      game = this.responseText
    }
  };
  xhttp.open('GET', 'games/' + $('.meta').html() + '.game', true);
  xhttp.send();
}

My issue is that the variable game is being treated as a string instead of an array, even though this.responseText is actually a valid array. Is there a way to make JavaScript recognize this.responseText as an array when assigning it to game?

Answer â„–1

Due to the utilization of ' for string delimiters, the function JSON.parse will not be effective

Consider the following alternative, depending on the nature of the data:

game = JSON.parse(this.responseText.split("'").map(function(x) { return x.replace(/"/gm, "'"); }).join('"'));

It is important to note that if any values contain ' or ", this method may not work effectively

Alternatively, a much simpler solution involves using eval ...

eval("game=" + this.responseText);

Exercise caution when utilizing eval

Answer â„–2

The value of xhttp.responseText is always a string, but you can convert it to an array by using the JSON.parse(xhttp.responseText) method. To successfully use JSON.parse, the data must first be encoded in JSON format on the server. In PHP, this can be achieved using the json_encode function, as shown below:

// PHP
$response = array("a", "b", "c", "d");
echo json_encode($response);

By utilizing JSON.parse on the client side, you will receive the array ["a", "b", "c", "d"].

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

Emulate clicking a radio button (using PHP and JS)

For the past week, I've been struggling to solve this issue with no luck. I admit that I am new to this area, so I ask for your patience. My current problem involves using TastyIgniter, an online food ordering system. In order to add items to the car ...

Ensure that only valid numbers can be inputted into an HTML number type field

My input number is as follows: <input type="number" id="quantity" name="quantity" (change)="firstRangePointChanged($event)" > I need to ensure that users cannot input invalid values like --99 (--) instead of ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Button for searching through the Bootstrap navigation bar

I'm currently working on adding a search menu to the navbar in two different designs - one for screens below 767px and another for screens above 767px. Although I have been successful in expanding the search bar, I am facing issues with the correct p ...

Converting UK DateTime to GMT time using Angular

I am currently working on an angular project that involves displaying the start and end times of office hours in a table. For instance, the office operates from 8:30 AM to 5:30 PM. This particular office has branches located in the UK and India. Since u ...

Personalize the appearance of your stackLabels in Highcharts with dynamic customization options

I recently created a bar graph using Highcharts. You can check it out here: http://jsfiddle.net/v1rbz41q/3/ Here's the code snippet I used: chartw.yAxis [0] .options.stackLabels.formatter = function () {              return "werfdc";   ...

Using Bootstrap Select with a callback function

I am currently working with 2 Bootstrap Select dropdowns. One dropdown contains a list of countries, while the other contains a list of states. The country list is static and loads when the page is loaded. On the other hand, the state list is populated dyn ...

Associating functions with events within objects

I am encountering a unique issue with jQuery and JavaScript in general. Currently, I am developing a JS file that allows me to create portlets for a client's website. I am utilizing SignalR to send updates to the users. The code snippet below is cau ...

Extract user's location using JavaScript and transfer it to PHP

My goal is to utilize JavaScript to retrieve the latitude and longitude, then compare it with the previous location, similar to how Facebook authenticates logins from different devices. To accomplish this, I have implemented 2 hidden fields which will capt ...

What is the process by which a JavaScript Date object is converted to a string when you log it to the

Whenever I create objects in JavaScript and output them to the console, I typically see a JavaScript object displayed. For instance: var myObj = { bla: "foo" } console.log(myObj); This code will display: { bla: "foo" } However, whe ...

retrieving multiple values in ajax call and processing them in controller function

I'm facing a challenge in Laravel when it comes to sending multiple input options (generated by a foreach loop) through an ajax call. The goal is to send multiple values and loop through them in the ajax call to effectively pass them to the controller ...

Sending various values to a JavaScript function

I am working with a function that looks like this: //Function Call with Single Parameter responses(baseURL); //Function Definition function responses(baseURL) { $.ajax({ url: baseURL, type: "get", cache: false, header ...

Tips for Iterating through Nested Arrays using the Inside Array in a Dynamic Way

I am facing an issue with my code as it lacks flexibility when a new array is added to the nested array, in which case the new array is not considered. My main concern is how to access the elements of each nested array simultaneously. Here's an examp ...

Creating NextJS Route with Dynamic Links for Main Page and Subpages

In my NextJS project, I have dynamic pages and dynamic subpages organized in the following folders/files structure: pages ├── [Formation] ├── index.js │ ├── [SubPage].js Within index.js (Formation Page), I create links like this: < ...

Fetch information on demand using AJAX

I currently have a webpage that utilizes ajax to fetch server information from a php script. Here is an example of the ajax call: $.ajax({ url: "broker.php?action=getServers", type: 'get', dataType: 'html', ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Is there a way to click on an ajax link?

AjaxOptions ajaxMainContent = new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "main_content" }; @Ajax.ActionLink("start new game", "Game", ajaxMainContent) I am looking for a way to trigger this action in javascript. function startNewGame(cost) ...

Update the page content dynamically using Ajax when clicking on the navigation menu

I am looking to dynamically change the content of my list based on what the user clicks in my navigation menu. I am new to Ajax and still learning about it. I don't want the site to reload, so using only PHP is not the solution for me. If someone co ...

Guide on linking a textarea with a boolean value in the child component

I have created a form component consisting of two components. The first component looks like this: <template> <div class="flex flex-col items-center justify-center gap-2"> <div class="flex w-[80%] items-center justify-ce ...