colin
colin

Reputation: 65

problem extracting JSON data from server PHP array

I am trying to extract a stock price from a JSON response created by a PHP file on my server. I have described 2 tests below, Test 1 extracts the JSON data from a file successfully, Test 2. getting the JSON data from aPHP script on the server results in errors. I have worked on this for ages so any help in getting a solution would be hugely appreciated, many thanks.

I am using Wordpress and Woody Universal Snippets on the client, ultimately I will integrate the code into a datatables script once working.

Test 1. get the JSON data from a text file on the server works 100% below

<script>

var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");

//ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
//ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");   
ourRequest.onload = function() {
console.log(ourRequest.responseText);
    var ourDataJSON = JSON.parse(ourRequest.responseText);
}
ourRequest.send();  
</script>

JSON File ajax_stock_holdings_json1.txt

[
  {
    "symbol": "CTY.LSE",
    "price" : "430"
  }
]

Test 2. Fails comment out line

ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");

uncomment line

ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");

run local client script below

<script>

var ourRequest = new XMLHttpRequest();
//ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings_json1.txt");

ourRequest.open("GET", "../../Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");
//ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php");   
ourRequest.onload = function() {
console.log(ourRequest.responseText);
    var ourDataJSON = JSON.parse(ourRequest.responseText);
}
ourRequest.send();  
</script>

Server PHP File

<?php
 /* Loads the WordPress environment and template */
require( '../../wp-blog-header.php' );

global $current_user;
wp_get_current_user();

// DataTables PHP library
include( "../lib/DataTables.php" );

$json_array = array();
$stock_id = 709; // CTY.LSE

try {
    $pdo = new PDO(strtolower($sql_details['type']) . ":host=" . $sql_details['host'] . ";dbname=" . $sql_details['db'], $sql_details['user'], $sql_details['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully" . "\n\n"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }

$result = $pdo->query("SELECT id, symbol, name, price FROM dm_stocks WHERE id = $stock_id");
        foreach ($result as $row) {

                echo "" . $row['id'] . "";
                echo " : " . $row['symbol'] . "";
                echo " : " . $row['name'] . "";
                echo " : " . $row['price'] . "\n";

        array_push( $json_array, array('symbol'=>$row['symbol'], 'price'=>$row['price'] ) );
        }

echo json_encode($json_array); 

?>

Results are ajax_stock_holdings1.php Network Response

Connected successfully

709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]

Console Log

JQMIGRATE: Migrate is installed, version 1.4.1
(index):294 Connected successfully

709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]
VM2786:1 Uncaught SyntaxError: Unexpected token C in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.ourRequest.onload ((index):295)

Uncommenting line using full path to PHP

ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php"); 

results in the following error

Console displays

Access to XMLHttpRequest at 'https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php' from origin 'https://www.dividendlook.co.uk' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have tried configuring HTTP Headers plugin to no avail, this may be down to an infinite number of configuration options, knowing which if any will clear my errors.

I have added code to my server PHP file to fix the Access-Control-Allow-Origin problem to as follows :-

<?php
 /* Loads the WordPress environment and template */
require( '../../wp-blog-header.php' );

global $current_user;
wp_get_current_user();

// DataTables PHP library
include( "../lib/DataTables.php" );

// HTTP Header 

header('Access-Control-Allow-Origin: https://dividendlook.co.uk');

$json_array = array();
$stock_id = 709; // CTY.LSE

...etc as before

Failed to load resource: the server responded with a status of 404 ()
jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
(index):1 Access to XMLHttpRequest at 'https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php' from origin 'https://www.dividendlook.co.uk' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://divdendook.co.uk' that is not equal to the supplied origin.
generic-no-float.css:1 Failed to load resource: the server responded with a status of 404 ()

substituting following line to PHP file instead of previous with sitename

header('Access-Control-Allow-Origin: *');

results in error

Failed to load resource: the server responded with a status of 404 ()
jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1
(index):294 Connected successfully

709 : CTY.LSE : City of London Investment Trust Plc : 405.5
[{"symbol":"CTY.LSE","price":"405.5"}]
(index):1 Uncaught SyntaxError: Unexpected token C in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.ourRequest.onload ((index):295)
generic-no-float.css:1 Failed to load resource: the server responded with a status of 404 ()

I have added the following code to the end of .htaccess which has fixed the CORS policy: The 'Access-Control-Allow-Origin' problem, now the error is

''' Failed to load resource: the server responded with a status of 404 () jquery-migrate.min.js?ver=1.4.1:2 JQMIGRATE: Migrate is installed, version 1.4.1 (index):290 ourRequest.responseText >>>>>:[{"symbol":"CTY.LSE","price":"405.5"}]:<<<< generic-no-float.css:1 Failed to load resource: the server responded with a status of 404 () '''

The JSON is however being read by the client script OK

New client script

<script>    
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings1.php"); 
ourRequest.onload = function() {
console.log("ourRequest.responseText >>>>>:"+ourRequest.responseText+":<<<<");
}
ourRequest.send();  
</script>

Upvotes: 0

Views: 126

Answers (1)

codemon
codemon

Reputation: 72

On your server ,PHP. Add those required headers. Browsers reject response from different origins. To get this work, Set the Access-Control-Allow-Origin to '*'. This was any request from any origin gets served a response.

Upvotes: 1

Related Questions