0

I am unable to extract the JSON property value from the JSON returned from my server running in a wordpress environment.

Client Universal Woody Snippet Script

<html>
<body>

<h2>JSON string output from a JavaScript object.</h2>

<h4>JSON String Value is:</h4><p id="demo"> </p>
<h4>JSON Symbol2 Value is:</h4><p id="json_symbol2"> </p>
<h4>JSON Symbol Value is:</h4><p id="json_symbol"> </p>
<h4>JSON Price Value is:</h4><p id="json_price"> </p>

<script>    
var ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_holdings2.php"); 
ourRequest.onload = function() {
var obj =   ourRequest.responseText;
var myJSON =    JSON.parse(JSON.stringify(obj));
//var myJSONprice =     JSON.parse(JSON.stringify(obj.price));
console.log( myJSON );

console.log( myJSON.symbol );
console.log(myJSON.price);

document.getElementById("demo").innerHTML = myJSON;
//document.getElementById("json_symbol2").innerHTML = myJSONprice;
document.getElementById("json_symbol").innerHTML = myJSON.symbol;
document.getElementById("json_price").innerHTML = myJSON.price;
}
ourRequest.send();  
</script>
</body>
</html>

Server PHP Script

<?php

/*
 * ajax_stock_holdings2.php
 */
$filename = 'ajax_stock_holdings2.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" );


//$stock_id = $_GET['stock_id']; // manually setting variable for testing
$stock_id = 1293;
$stock_array = array();

// check if variable is NOT blank pass JSON back to client 
if ($stock_id  <> "") {

//echo "the value of stock_id is :" . $stock_id . ":" . "\n";

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 $filename . "Connected successfully" . "\n\n";
    }
catch(PDOException $e)
    {
//    echo $filename . "Connection failed: " . $e->getMessage();
    }

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

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

echo json_encode($stock_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK); 
}

?>

JSON returned

[
    {
        "symbol": "GSK.LSE",
        "price": 1744
    }
]

Output from client script

Test JSON
JSON string output from a JavaScript object.
JSON String Value is:
[ { "symbol": "GSK.LSE", "price": 1744 } ]

JSON Symbol2 Value is:
JSON Symbol Value is:
undefined

JSON Price Value is:
undefined

I have tried uncommenting the commented lines for Symbol2 which results in an error i.e. assigning the property value before stringify

VM23451:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.ourRequest.onload ((index):303)

line 303 is

var myJSONprice =   JSON.parse(JSON.stringify(obj.price));

Any help on this issue is much appreciated, many thanks Colin

I am trying to integrate the above code to write the price as message on the datatables.net editor modal, the client snippet extract is below

    editor.dependent( 'dm_transactions.stock_id', function ( val, data, callback ) {
    $.ajax( {
        url: '../../Editor-PHP-1.9.0/controllers/ajax_stock_transactions.php',
        dataType: 'json',
        // pass stock_id value to server php script
        data: { "stock_id": val },
        success: function (json) {          
            callback(json);

ourRequest = new XMLHttpRequest();
ourRequest.open("GET", "https://dividendlook.co.uk/Editor-PHP-1.9.0/controllers/ajax_stock_transactions.php");  
ourRequest.onload = function() {
obj =   ourRequest.responseText;    
myJSONobj =     JSON.parse(obj);
myJSONstr =    JSON.parse(JSON.stringify(obj));

console.log( myJSONobj );
console.log( myJSONstr );

console.log(myJSONobj[0].symbol);
console.log(myJSONobj[0].price);

document.getElementById("json_obj").innerHTML = myJSONobj;
document.getElementById("json_str").innerHTML = myJSONstr;
document.getElementById("json_symbol").innerHTML = myJSONobj[0].symbol;
document.getElementById("json_price").innerHTML = myJSONobj[0].price;
}
ourRequest.send();  

editor.field("dm_transactions.price").set(myJSONobj[0].price);
    }),{
        event: 'keyup change'
    };

    editor.dependent('dm_transactions.stock_id', function ( val, data, callback ){
        return { messages: { 'dm_transactions.price': 'Yesterday Close : ' + myJSONobj[0].price }};

    },{
    event: 'keyup change'
    });

The error generated is below

(index):570 Uncaught TypeError: Cannot read property '0' of undefined
    at (index):570
    at HTMLDivElement.<anonymous> (dataTables.editor.js:2602)
    at HTMLDivElement.dispatch (jquery-3.3.1.js:5183)
    at HTMLDivElement.elemData.handle (jquery-3.3.1.js:4991)
    at Object.trigger (jquery-3.3.1.js:8249)
    at HTMLSelectElement.<anonymous> (jquery-3.3.1.js:8327)
    at Function.each (jquery-3.3.1.js:354)
    at jQuery.fn.init.each (jquery-3.3.1.js:189)
    at jQuery.fn.init.trigger (jquery-3.3.1.js:8326)
    at dataTables.editor.js:9159

line (index):570 is below

editor.field("dm_transactions.price").set(myJSONobj[0].price);

Any help in how I integrate this code into my datatables code shown above, would be appreciated thanks Colin

colin
  • 65
  • 2
  • 12
  • 1
    Your PHP script returns an array (`array_push`, `[ { ... } ]`). Treat it accordingly. – Andreas Dec 21 '19 at 11:59
  • Get rid of the JSON.stringify(object) as the response is already a string `var myJSON = JSON.parse(JSON.stringify(obj));` Should be `var myJSON = JSON.parse(obj);` Now you stringify something thats already a string – Danny Ebbers Dec 21 '19 at 12:01

1 Answers1

2

The response from your PHP code is an array of associative arrays, which once json_encoded becomes an array of objects. So to access the individual values you need to iterate over the array, or, if there will only be one row returned from the query, you can simply use the [0] element e.g.

console.log(myJSON[0].symbol);
console.log(myJSON[0].price);
Nick
  • 138,499
  • 22
  • 57
  • 95
  • Hi Thanks, I appreciated that the JSON was an array, my mistake, the combination of changing MyJSON = JSON.parse(obj) and myJSON[0].price etc has solved the problem. Many Thanks Colin – colin Dec 21 '19 at 12:16
  • I have added some additions to the call showing my attempt to integrate the code into my datatables.net code, details shown above, any help on thsi would be appreciated thanks Colin – colin Dec 21 '19 at 14:59
  • Should I raise another call for this question ? Colin – colin Dec 21 '19 at 15:01
  • @colin sorry about the slow response - been sleeping. It looks like you are trying to set `editor.field("dm_transactions.price").set(myJSONobj[0].price);` outside the callback from sending `ourRequest`, so `myJSONobj` won't be set at that point. – Nick Dec 21 '19 at 21:57
  • Hi Nick, thanks for your reply, sorry for my delay, I have tried using global variables setting value within callback and setting the editor field value to the variable to no avail, so I may need to go back to datatables.net for a solution. Thanks Colin – colin Dec 27 '19 at 10:58
  • @colin yeah - if trying to set the value inside the callback didn't work, then it's probably time for a new question. Sorry I couldn't be of more help... – Nick Dec 27 '19 at 11:03
  • Hi Nick, I appreciate your help, I have moved issue forward. Thanks Colin – colin Jan 09 '20 at 12:24