Retrieving PHP information using Javascript and storing it in an array

I have a PHP script that fetches data from a server and stores it in an array. I then convert this array into a JSON object using the following function:

echo json_encode($result);

Now I want to access this array in my JavaScript and display it. I want to save it as a variable in the form of an array like this:

 data = [ "xxxx" , "ssss",];

Instead, I could simply call my function that retrieves the array data, making it look like this:

data = myfunction ;

Here's what I have tried so far:

 function reqListener () {
     console.log(this.responseText);
         }

        var oReq = new XMLHttpRequest(); //New request object
      oReq.onload = function() {


       };
        oReq.open("get", "http://myserver.com/myscript.php", true);

oReq.send();

and

function getdata(url) {
jQuery.ajax(
        {
            type: "GET",
            url: "http://myserver.com/myscript.php/",
            dataType: "text",
            success: function (response) {
                var JSONArray = jQuery.parseJSON(response);
                connsole.log(JSONArray);
                }
        });
    }

Unfortunately, none of these methods seem to be working as expected. I keep getting 'undefined' instead of the arrays. I would greatly appreciate any help or ideas on how to solve this issue.

Edit: Here is the PHP code snippet:

<?php 
 error_reporting(0);
 $html = file_get_contents("url here");

$dom = new DOMDocument();
$dom->loadHTML($html);

 $tbodyRows = $dom->getElementsByTagName( 'tbody' )
             ->item( 0 ) // grab first tbody
             ->getElementsByTagName( 'tr' );

$result = array();
foreach( $tbodyRows as $tbodyRow )
{
  $result[] = $tbodyRow->getElementsByTagName( 'td' )
                     ->item( 2 ) // grab 3rd column
                     ->nodeValue;
 }


echo json_encode($result);
 ?>

Answer №1

Give this code a shot:

function fetchDataFromUrl(url) {
  console.log('Fetching data');
  jQuery.ajax({
    type: "GET",
    url: "http://myserver.com/myscript.php",
    dataType: "text",
    error: function (xhr) {
      console.log('Error',xhr.status);
    },
    success: function (response) {
      console.log('Success',response);
    }
  });
}

Check the browser's console for any messages. If you don't see Error or Success, your code isn't running properly.

Answer №2

I've previously tackled a similar task and found a solution that I'd like to share with you.

In the code snippet below (get_categories.php), I'm fetching data from the database and storing it in an array. The data is then returned after being encoded as JSON.

$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $dataArray[] = $row;
    }
    echo json_encode($dataArray);
}

Subsequently, in my JavaScript code, I retrieve the data using the following method.

$.ajax({
    url: "/get_categories.php",
    type: "GET",
    dataType: "json",
    success: function (categories) {
        for (var i = 0; i < categories.length; i++) {
            console.log(categories[i]);
        }                
    },
    error: function (jqXHR, textStatus, errorThrown) {
        // Error handling code
    }
});

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

How to resolve the issue of "Fixing 'Unhandled Runtime Error TypeError: event is undefined'"

Today I encountered this error: Unhandled Runtime Error TypeError: event is undefined and couldn't find a solution online Here's the code snippet: import { ethers } from 'ethers' import { create as ipfsHttpClient } from 'ipfs-h ...

Deploying React application to Heroku resulted in an Application Error even though there were no errors during the build

I'm facing some issues while deploying my React app on Heroku. Even though the app compiles and builds successfully on both my local server and Heroku, it still shows an error. I've added https://github.com/mars/create-react-app-buildpack.git to ...

Odd digits popping up in array

Hey everyone, I'm pretty new to programming and I have a question. I've written a program where a user can input the position of something, and I believe it should involve using an array. Here's what I have so far: #include <stdio.h> ...

Is there a way to use JavaScript to determine if GEARS is already installed on a system?

Does the existence of windows.gears not equal to undefined or what??? I am simply looking to use javascript to determine true or false based on whether the person has google Gears installed. ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

The type unknown[] cannot be assigned to type React.ReactNode

import * as React from 'react'; import { List, ListItemButton, ListItemIcon, ListItemText, ListItem} from '@mui/material'; import LightbulbOutlinedIcon from '@mui/icons-material/LightbulbOutlined'; import NotificationsNoneOutl ...

PHP is automatically converting all of the float values in my array to integers

I am encountering an issue with the following code: $val = (float) $desc; if (!isset($runepage['statistics'][$key])) { $runepage['statistics'][$key] = (float) 0.0; } $runepage['statistics'][$key] += $val; Her ...

Implementing a function in ReactJS that is activated by multiple buttons

Apologies for the unclear title. My issue revolves around having three different button tags, each of which should send a unique argument to the function selectSupplier(). However, no matter which button is clicked, only the last value ("ultramar") is be ...

Why is Ajax having trouble showing PHP's JSON data? What could be causing the issue with the JSON format?

After thoroughly reviewing all related questions on the topic, I still haven't been able to find a solution. When I attempt to integrate JSON into my PHP and AJAX code for passing data, that's when the trouble begins. Here is the AJAX portion o ...

JavaScript - Deleting the last element of an array

I have currently integrated a third-party API to visualize data using Highcharts. This external API provides data specific to the current month, such as March, April, May, and so on. graphArrOne contains an array with 251 elements. graphArrTwo contains ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

How come I am unable to make PHP display a specific JSON element for me?

Wow, working with JSON data can really consume my day. Is it meant to be this challenging? Probably not. So, I have a URL that contains a JSON dataset. The structure looks like this: jsonval={%22Fname%22:+%22kjhjhkjhk%22,+%22Lname%22:+%22ghghfhg%22,+%22c ...

Forcing the Json Serializer to output a specific datetime format of (yyyy-mm-ddThh:mm:ss.msmsmsZ)

Creating a new instance of MyClass using the following code snippet: MyClass theSession = new MyClass() { accountId = 12345, timeStamp = DateTime.Now, userType = "theUserType" }; Serializing the data using JavaScriptSerializer: System.Web.Sc ...

Javascript operations for duplicating and altering arrays

In my Angular application, I am working with an array called subAgencies that is connected to a datasource. I need to implement 2-way binding on this array. Currently, I have a method in place where I copy the contents of the original array to a new one, ...

How to properly format an HTML input box for numeric entry and ensure correct formatting of the minus sign

I need assistance with formatting an HTML text input box to only accept numeric values using JavaScript. Specifically, the input should allow digits, a minus sign, or a dot/comma (which will be converted to a dot). However, I want to prevent multiple conse ...

How to modify array in React using the useState hook?

Hello, I'm currently facing an issue where I am attempting to remove an object and set new data, but each time I do so, it reverts back to the previous state. For example, if I remove "emma" from the array ([ {name:"red"},{name:"reeed"},{name:"emma"} ...

What is the process for converting a JSON File into an array using javascript?

Hey there, I'm new to programming so please bear with me XD. I've been struggling for 2 days trying to figure this out with no luck. So here's the deal - I have a chart in JavaScript that is pulling data from a file called test.json, which ...

Switch up the sequence of selected/appended SVGs in D3

In this dot matrix visual example, different colored circles represent funding percentages from three countries: USA, Canada, and Mexico. The gray circles indicate the remaining funding to be raised. The code snippet showcases how the circles are mapped ba ...

transforming a Java object into JSON format with a custom object identifier

Is there a way to transform a Java object into JSON with a different object name? Take for instance: public class MetaProfileResponse { private Boolean tour ; private Integer maxFreeUser; private Boolean paid; private Integer status; } ...

The focus is being lost on the ng-model when used within an ng-repeat

Within my JavaScript code, I am initiating a new question object like this: $scope.newQuestion = { answers: [] }; This is how it reflects in the HTML: <div class="row" ng-repeat="answer in newQuestion.answers"> <div class="input-field col m ...