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