Retrieve an array from JSON encoding using AJAX

I have been attempting to retrieve 4 JSON arrays stored in a separate file and include them in my main file using an AJAX request. However, I'm facing difficulties storing these arrays into variables and logging them in the console. Here are the results from the JSON file:

[[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5], 

[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2], 

[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32...

<p>This is how I attempted to incorporate them onto my main page:</p>

<pre><code>function callback(response) {
      var array1 = response[0];
      var array2 = response[1];
      var array3 = response[2];
      var array4 = response[3];
      console.log(array1);
}

$.ajax({
  url: 'loadchart.php',
  success: callback
});

But when trying to retrieve all elements of array1, I only get an opening bracket:

[

Snippet from loadchart.php:

<?php 

  session_start();

  if(!isset($_SESSION['usersId']))
  {
    header("Location: ../index.php");
    exit();
  }
  else
  {
    include_once 'includes/dbh.inc.php';
  }

  $id = $_SESSION['userId']; 
  $dBname = "infosensor";
  $conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);

  $sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";

  $result = mysqli_query($conn, $sql);
  $jsonsensor1 = array();
  $jsonsensor2 = array();
  $jsonsensor3 = array();
  $jsonsensorsum = array();

...

Answer №1

Include dataType attribute with the value of "json":

$.ajax({
      url: 'loadchart.php',
      dataType:"json",
      success: handleData
    });

Answer №2

To properly handle your json array, utilize JSON.parse method in your function as demonstrated below:

function processData(data) {
  var result = JSON.parse(data);
  var item1 = result[0];
  var item2 = result[1];
  var item3 = result[2];
  var item4 = result[3];
  console.log(item1);
}

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

Encountering a Node Js post handling error with the message "Cannot GET /url

This is my ejs file titled Post_handling.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>POST-Handling Page</title> </head> <body& ...

p:inputText failing to trigger listener for p:ajax

I am looking to add custom filtering to a p:dataTable. Within the table's header, I have included a p:inputText element that I want to use for ajax filtering. However, I am encountering an issue where the bean method is not being invoked by the p:ajax ...

Generate a variety of requests with Axios

I have a task where I need to send multiple Axios requests, but the number of requests can be completely random. It could range from 0 to even millions. Once all the requests are completed, I then need to perform an action, such as updating my state, which ...

The integration of Firebase Google Auth seems to encounter issues when used on the Vercel

My experience with Vercel deployment has been quite interesting. While I find that Google authentication works seamlessly on localhost, it seems to encounter an issue when deployed on Vercel. Specifically, after logging out, the currentUser variable always ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

Javascript scoping issue with a function that generates and returns other functions

I am facing an issue with my function where I keep getting 2 in the alert message every time. It seems like a variable scope problem, but I haven't been able to resolve it yet. var someObj = {"a" : 1, "b" : 2}; function retrieveData(obj){ var func ...

Validating IDs by comparing them with one another. If the IDs do not match, an error message will be displayed. If they do match, the corresponding data will

Contents: Overview of the code's functionality. CODE Achievements. Bugs Expected vs. Actual Output Attempts to troubleshoot the errors 1. Overview of the Code's Functionality This system functions as a clock in and out mechanism utilizing an R ...

Issue in Babel: The preset 'latest' could not be located in the directory even though it was installed globally

I executed a global installation of Babel using: npm install -g babel-cli npm install -g babel-preset-latest Although it is generally not recommended to install Babel globally, I find it preferable in order to maintain a clean directory structure without ...

Performing a bulk update using the array provided as the base for the update statement

In my database, there is a table called sched that I frequently need to update. To facilitate this process, I have created an HTML interface that displays the current values of the sched table for users to edit. Upon making changes, scripts are triggered ...

What could be the reason for document.body.style.backgroundColor not working properly?

I am currently experimenting with a logic that triggers the screen to turn black upon pressing the print screen key. Despite changing the background color, it is not functioning as expected. The console has detected a change in value. What could be going ...

Error occurs when an arrow function is called before its function definition

console.log(addB(10, 15)); function addB(a, b) { return a + b; } console.log(addC(10, 15)); const addC = (a, b) => { return a + b; }; I attempted to convert a function into an arrow function and encountered the error "Cannot access 'addC&ap ...

loop through nested arrays

My goal is to use ng repeat in Angular to iterate through a child array of a multidimensional array. The json object I am working with is as follows: $scope.items = [{ "id":1, "BasisA":"1", "Basis":true, "personSex": ...

initiating an event within a modal controller

I have a $scope.$on callback function in my mainController. It works perfectly whenever I call it from each controller, but when I call it from a modalController after opening the modal, it doesn't work: define(['app', 'jquery'], ...

"Unexpected error: .jqm is not defined as a

Having an issue with a jqm function that I need help with. <span class="smaller gray">[ <span class="blueonly"><a href="javascript:void(0)" rel="nofollow" onclick="javascript:jQuery(\'#s ...

What techniques can be used to ensure an element remains visible within the viewport

I am currently working with an HTML element that is displayed when a button is clicked, similar to a popup. My goal is to determine if the element is within the browser's viewport and then position it accordingly inside the viewport. Is there a proper ...

Encountering an issue with Node JS request and cheerio while parsing an HTML page

Greetings all, I am currently attempting to parse a website using Node.js (utilizing request and cheerio). The issue I am encountering is that I am trying to extract the href from the site, but I can only find it within the site's window. Unfortunatel ...

Unable to retrieve uploaded files within the controller

Update with the latest code that helps solve my problem $scope.uploadedFiles = []; $scope.upload = function(files) { $scope.uploadedFiles = files; angular.forEach(files, function(file) { if (file && !file.$error) { ...

What are some tactics for circumventing the single-page framework behavior of next.js?

How can I change the behavior of next.js to load each URL with a full reload instead of acting like a one-page framework? ...