Getting data out of this array in JS - javascript

Finally i get some output out of PHP instead of just the word "array". This took me a day, AAAAHHHH.
(see here for the solution)
So this is the return value from a XMLHTTP request (to PHP), via a callback in JS. I got it with print_r in PHP.
I post a snippet of the results here.
My new question:
what is this data structure made of?
how to get elements out of this structure, such as CourseID (in JS)?
[0] => Parse\ParseObject Object
(
[serverData:protected] => Array
(
[CourseID] => DEMO2
[EndDate] => DateTime Object
(
[date] => 2017-03-31 10:26:00.000000
[timezone_type] => 2
[timezone] => Z
)
[InfoTitle1] => Welcome
[InfoText1] => Welcome to your course, called "sense & sales".
[Admin] => Remco#Demo1
)
My PHP code is
function getGroups(){
$query = new ParseQuery("CourseInfo");
$query->equalTo("Admin", "Remco#Demo1");
$results = $query->find();
// echo $results // this lead to the string "array"
//print_r($results); // this leads to the complicated array
//echo "<script>\r\n var phpOutput = " . json_encode($results) . ";\r\n console.log(phpOutput);\r\n</script>";
// this leads to [{},{}];
}

What you want is a JavaScript Object, so you need to use JSON.
(JSON means JavaScript Object Notation.)
PHP has a json_encode function, which will do the work for you: (http://php.net/manual/en/function.json-encode.php)
json_encode — Returns the JSON representation of a value
Try this:
PHP:
echo "<script>\r\n var phpOutput = " . json_encode($output) . ";\r\n console.log(phpOutput);\r\n</script>";
Press F12 in your browser to open the browser's Console log window in Developer Tools to see the new JavaScript Object.

You may want to convert your PHP object to JSON first via json_encode().
This will allow you to easily work with it in JavaScript like you normally would with any JavaScript object.

I stopped trying to work with this array/object in JS. But instead i managed it on the PHP side and sent the results to JS.
Now it is all simple. (-;

Related

Calling JSON.parse on php returned array, some numbers parsed as INT, others parsed as STRING

Looking for an explanation rather than an answer here :)
I have this php script that is called with jquery's AJAX
$query = 'SELECT MONTH(PRSD#) as "Monat", CAST(AVG(GASVBR) as DECIMAL(10,3)) as "Gas", CAST(AVG(OLVBR) as DECIMAL(10, 3)) as "Öl", CAST(AVG(STROVBR) as DECIMAL(10,3)) as "Strom" FROM swind.gwenergy GROUP BY YEAR(PRSD#), MONTH(PRSD#) ORDER BY MONTH(PRSD#)';
$dbReturn = $database->execute($query, array());
$jsonArray = array();
while ($row = db2_fetch_assoc($dbReturn)) {´
echo json_encode($jsonArray);
}
When I call in the JS side of things:
let parsedData = JSON.parse(jsonData);
I am returned with this:
{Monat: 2, Gas: '13750.607', Öl: '1447.432', Strom: '3901.051'}
How come the Monat value is not in quotes?
I thought that maybe because the $query in the php script was returning DECIMAL(10,3) but when I replace it with FLOOR(... the JSON.parse still wrapped the value in quotes. Is this related to the $query response, or is this a JSON.parse action?
Look forward to hearing other ideas :) Thanks! -Boogabooga
I've faced a similar problem.
You can check the data type on PHP with gettype()
Note that since PHP 5.3.3, there is a flag for auto-convert numerical numbers when using json_encode.
echo json_encode( $jsonArray, JSON_NUMERIC_CHECK );
This should do the work for you.

From JSON to Actionscript

Good Day,
is it possible to convert an object to an Actioscript model in Javascript ?
I have this:
const user = [{"id":"1","name":"Doe","firstname":"John","tel":"1112223333"}];
I would like to have this:
const user = [{id:1,name:"Doe",firstname:"John",tel:1112223333}];
When I use user.replace(/"/g,""); I have the error:
user.replace is not a function
But this is where I'm stuck. I don't know how to do it if I can't use replace.
To put you in context, the object is fetched via ajax and PHP by doing echo json_encode($to_encode);
Thank You for your help! :)
Its a JSON.parse()
Updated
convert the string to number
const user ='[{"id":"1","name":"Doe","firstname":"John","tel":"1112223333"}]';
var res =JSON.parse(user)
res.forEach(function(a){ //convert the string to number
Object.keys(a).forEach(function(key){
a[key] = Number(a[key])||a[key]
})
})
console.log(res)
Check you broswer console.log F12 is showen like this

Javascript array without quotes

I've been pulling my hair out trying to figure this out.
I'm using ZingChart to plot some data from a MySQL query. I put the data into a PHP array, and then use:
var myData = <?php echo json_encode($combined); ?>;
to put it into a javascript array.
If I do:
document.write(myData[0]);
then it shows the correct value for that index. When I try to use the array with the ZingChart's JSON, I see that it puts quotes around all the data, which for some reason it doesn't like. If I manually remove the quotes using notepad, the data displays great, so I know it's just a matter of getting rid of these quotes somehow.
Here's how it looks, for example, when I view the source from the page:
var myData = [["1466766034467","71.191"],["1466766094482,71.1986"]];
I've tried many ways and spent many hours trying to get the data passed into JSON without the quotes, but I know just enough to be dangerous, so hopefully someone can guide me.
document.write(myData[1]);
will result: 1466766094482,71.1986
Thanks in advance.
Assuming you are running a reasonably current version of php you can add JSON_NUMERIC_CHECK to json_encode() options argument
json_encode($combined, JSON_NUMERIC_CHECK);
See json_encode docs
Or in javascript iterate arrays and cast values to number using any variety of methods
myData.forEach(function(arr){
arr[0] = +arr[0];
arr[1] = +arr[1];
})
You can parse the String types into Int and Float. For your 2-item arrays, the following works with the map function:
myData.map(function(x){ return [parseInt(x[0]),parseFloat(x[1]) });
// or in ES6 notation
myData.map( x => [parseInt(x[0]),parseFloat(x[1])] );
General Solution
Inspired by #charlietfl's solution, here's a generic function parseNumeric for converting all numeric data within an array. It will recurse through any nested arrays it finds.
var myData = [["1466766034467","71.191"],["1466766094482","71.1986"]];
// Convert data to numeric, including recursion within nested arrays
// Usage parseNumeric( myData );
function parseNumeric(x,y,z) {
if( Object.prototype.toString.call( x ) === '[object Array]' ) {
x.forEach(function(c,i,a){numConvert(c,i,a)});
} else if ( typeof z != 'undefined' ) {
z[y] = +x
}
}
parseNumeric( myData );
// => [[1466766034467,71.191],[1466766094482,71.1986]];

How to parse my JSON string into a multidimensional array in Javascript after passing JSON string from php file with AJAX?

I am doing some testing before I run a full scale program, and good thing I am. I have been doing some tests to return a multidimensional array from my php file to my htm webpage. I have tested many things to narrow my issue down to JSON.parse(). Here is my PHP code in file response.php:
<html>
<head>
</head>
<body>
<?php
$test = array(
array("first" => "Aaron", "last" => "Rodgers"),
array("first" => "Willie", "last" => "Makit")
);
//header('Content-Type: application/json');
echo json_encode($test);
?>
</body>
</html>
and my output is normal:
{"0":{"first":"Aaron","last":"Rodgers"},"1":{"first":"Willie","last":"Makit"}} //New output as per object typecasting
Then on my htm file I am just trying to display the first name "Aaron" as an output after my button press. here is the code for my html and javascript:
<html>
<head>
<script type="text/javascript" language="javascript">
function ajaxTest(){
var testAjax = new XMLHttpRequest();
testAjax.onreadystatechange = function(){
if(testAjax.readyState==4)
{
var test1 = JSON.parse(testAjax.responseText);
document.getElementById("doIt").innerHTML = test1.row[0].first; //I believe my error might be an issue with my formatting on this line
}
}
testAjax.open("GET", "response.php", true);
testAjax.send(null);
}
</script>
</head>
<body>
<input type="button" value="try it" onclick="ajaxTest()"/>
<div id="doIt"></div>
</body>
</html>
I have tried displaying the raw json string and that works. But once I use JSON.parse() any data I try to display is blank. I have tried several formats including the following:
document.getElementById("doIt").innerHTML = test[0][1];
... = test[0].first;
... = test;
... = test.length;
But regardless of the format I get no output (that is visible at least). The part that puzzles me is that even my array.length will not display a value. I get no error messages, just a blank output. Thanks in advance for any pointers or fixes everyone.
edit: after type casting my outer array as an object I still only get blank outputs. I do however think typecasting was necessary in my case.
In the PHP file, remove the HTML tags. That will solve the problem. Otherwise when responseText is called from the .htm file the string will include the HTML tags and will cause a syntax error when the data is parsed with JSON.parse().
This is not an answer to your question - you've already solved the problem. But I wanted to follow up on a couple of comments, and an answer is the only way to do proper code formatting.
#hyphenbash made an excellent suggestion: wrap your array inside an object for the JSON output, instead of outputting the bare array. While JSON does allow an array at the top level (contrary to the comment that said this would be invalid JSON), there are advantages to using an object instead and putting the array as a property inside the object.
Consider the array version of your original JSON (before the (object) cast was added). It looked like this (with some formatting for readability):
[
{ "first":"Aaron", "last":"Rodgers" },
{ "first":"Willie", "last":"Makit" }
]
There is nothing wrong with that, but suppose you want to add something else to the JSON response that is not part of the array, perhaps some kind of status or error indication. There is no place to put it!
By contrast, suppose you wrapped the array in an object instead:
{
data: [
{ "first":"Aaron", "last":"Rodgers" },
{ "first":"Willie", "last":"Makit" }
]
}
Now if you want to add some other bit of information it's easy:
{
status: "test",
data: [
{ "first":"Aaron", "last":"Rodgers" },
{ "first":"Willie", "last":"Makit" }
]
}
The PHP code to generate this is a simple change from your original:
<?php
$test = array(
"status" => "test",
"data" => array(
array("first" => "Aaron", "last" => "Rodgers"),
array("first" => "Willie", "last" => "Makit")
)
);
echo json_encode($test);
?>
And it's equally easy to handle this in your JavaScript code:
var test1 = JSON.parse(testAjax.responseText);
document.getElementById("doIt").innerHTML = test1.data[0].first;
Note a couple of other little changes here that I recommend in JavaScript code:
Take out the quotes around the 0 - either will work, but it's customary to use numeric indices with an array.
Use .foo notation instead of ["foo"] when accessing object properties. Either one works here too, but .foo is customary and more concise.
It is somewhat confusing to switch between PHP and JavaScript, since JavaScript has separate concepts of arrays and objects, where PHP combines them both into one.

Getting value of msg in array javascript

I have the following array:
Array
(
[0] => Array
(
[id] => 179
[user_id] => 191
[behandeling] => msg
)
)
For some reason i can't get the value of 'behandeling' .. i have tried several ways, like:
console.debug(msg[0].behandeling);
Some more info about building the array:
$d[] = array('id' => $row['id'],
'user_id' => $row['user_id'],
'behandeling' => $row['behandeling']);
//print_r($d);
//echo json_encode($d);
If i use print_r($d), the value of behandeling = CORRECT.
If i use json_encode($d), the value of behandeling will be null..
EDIT:
I think i found the problem.. When submitting the data, the data is being send unescaped in this way:
var data = 'actie=Wijzig&module=treatment&treatments=' + treatment.val();
This means if there are certains characters which need to be escaped, & etc.. the data string gets broken... which results in null and/or half msgs...
EDIT2:
The finding described above is very important, but describes a different section of the site. Saving the data is going fine now, but still having difficulties returning the value of the data of SOME messages..
As stated in the comments that's a PHP array, you could try the following:
<script type="text/javascript">
var myArray = <?=json_encode($array)?>;
var behandeling = myArray[0].behandleing;
</script>
Update:
I believe Javascript is interpreting the JSON as a regular string due to your content-type header.
You should try adding
header('Content-Type: application/json');
when outputting your JSON.
Alternatively, if for whatever reason you can't change the headers and you're using jQuery you can try:
var parsed = $.parseJSON(ajaxResults);
var behandling = parsed[0].behandling;
Without jQuery you can use eval however there are security implications involved.

Categories