Getting value of msg in array javascript - 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.

Related

How do I access a JSON array in JavaScript

I have a PHP script to which I make an Ajax request, and most of it works okay, but I'm having trouble accessing an array in the data returned to the JavaScript function.
So, the PHP has a bunch of regular variables, and one array. The array, $places, has four elements, which each have three values, as so:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
A relevant excerpt of the PHP script is:
$encoded_places = json_encode($places); // if I don't do this then I end up with a value of "Array"
$qobject->name = "$name";
$qobject->multi = "$multi";
$qobject->places= "$encoded_places";
$myJSON = json_encode($qobject);
echo $myJSON;
In the JavaScript script (using JQuery), I successfully obtain the data from the Ajax request, and I can access all the data okay, except the $places data.
$.getJSON(url, function(data, status){
var stringified = JSON.stringify(data);
var parsedObj = JSON.parse(stringified);
var x = parsedObj.name; // alert(x); // which works fine
var myArray = new Array();
myArray.push(parsedObj.places);
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
}
... and the console will display what I'm expecting, namely:
[["z","815","1"],["w","2813","0"],["s","1582","2"],["b","1220","5"]]
However, I'm having difficulty accessing these values. For example, supposing I try to access the "815" portion of the first element, with something like: myArray[0][1], all I end up with is "[".
I guess somehow this whole piece of data is just a string, instead of an array, but I'm not familiar enough with JavaScript to quite know how to progress.
If, for example, I do this in the JavaScript script (hoping to see 815, 2813, 1582 and 1220 in the alerts) all I'll see is the single alert with "[". (i.e. it does the loop only once, and selects the character in position 1).
for(var i = 0; i < myArray.length; i++){
console.log(myArray[i]);
alert(myArray[i][1]);
}
I would very much appreciate someone explaining:
(a) how I can access the individual elements and values in JS
(b) how I can loop through them, although presumably once it's an array and not a string then the code above should do this.
Many thanks for any assistance.
Now Resolved:
As noted by #charlietfl, below, using quotes in
$qobject->places= "$encoded_places";
screwed things up, along with using json_encode on $places. However, without removing the quotes nothing worked either way. So, removed quotes and just used json_encode on the entire structure at the end, which now works fine.
So, the original snippet of code, given above, now looks like:
$qobject->name = $name;
$qobject->multi = $multi;
$qobject->places= $places;
$myJSON = json_encode($qobject);
echo $myJSON;
Change
$qobject->places = "$encoded_places";
To
$qobject->places = $places;
And get rid of the $encoded_places = json_encode($places); so that the one call to json_encode serializes the whole structure
Try this:
$.getJSON(url, function(data, status){
var parsedObj = JSON.parse(stringified);
console.table(parsedObj.places);
console.log(parsedObj.places)[0][0];
}
In the posted code's getJSON context, data is already a JSON string. So this line is redundantly stringifying your JSON string:
var stringified = JSON.stringify(data);
stringified is now set to a literal/escaped version of the valid JSON string from the data parameter:
[[\"z\",\"815\",\"1\"],[\"w\",\"2813\",\"0\"],[\"s\",\"1582\",\"2\"],[\"b\",\"1220\",\"5\"]]
When that double-stringified value is passed to JSON.parse for the parsedObj reference, it just becomes the original JSON string again (which looks deceptively correct in an alert box).
Strings are iterable in JavaScript, so the for loop was just going over the string.

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

Getting data out of this array in JS

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. (-;

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.

Categories