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);
?>