Access JSON array values? - php

eSo I've got some parsed php data whiched I've fetched from my database and then parsed to JSON with json_encode(). Then I've used JSONparse() to make objects of my array. My code looks like this:
$.get("fetchDatabase.php", function(data){
var parsedData = jQuery.parseJSON(data);
}
I'm left with the array parsedData which looks like this:
[
{"person0":{"name":["Erik Steen"],"age":["1"]}},
{"person1":{"name":["Frida Larsson"],"age":["1"]}},
{"person2":{"name":["Abdi Sabrie"],"age":["2"]}},
{"person3":{"name":["Achraf Malak"],"age":["3"]}},
{"person4":{"name":["Adam Anclair"],"age":["1"]}}
]
I've placed those arrays in an array named
var peopleArray= { people: [ parsedData ] };
So far so good. Now what I want is being able to access certain persons attribute. Like names or age. How do I target those attributes? I've tried to print those attributes with no luck. I tried:
alert (peopleArray.people[0].person1.name);
Whiched returns:
Uncaught TypeError: Cannot read property 'name' of undefined
How can I access those attributes?

Apart from the typo ("namn") the problem is you're putting an array inside an array:
var peopleArray = { people: [ parsedData ] };
Since parsedData is an array then what you end up with is a structure like this:
// peopleArray
{ people : [ [ { "person0" : ... }, ... ] ] }
// oops -----^
See the problem? Since parsedData is a already an array the correct code would be:
var peopleArray = { people: parsedData };

Related

Loop AJAX Response from php

I want to loop ajax response
response = [
["u.profile"],
["r.useractivity"],
["i.items_job"],
["i.setup"],
["search"],
["i.items_assortment"]
]
I want data = u.profile;
data = r.useractivity;
etc
Tried Method :
$.each(response,function(key,value){
console.log(key+":"+value);
});
Getting error in console
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [["u.profile"],["r.useractivity"],["i.items_job"],["i.setup"],["search"],["i.items_assortment"]]
The problem is that your response var is an array of arrays (an object) and the default keys are integers.
It would be an easier (and better) way if you could change it into an array of strings like this one :
var response = ["u.profile",
"r.useractivity",
"i.items_job",
"i.setup",
"search",
"i.items_assortment"];
With this, you can easily loop your response like this :
for(var info in response)
console.log(info+':'+response[info]);
Hope this will help !

jQuery-UI Autocomplete Using URL Source Works With Array of Strings But Not Array of Objects

Using jQuery 1.7.2 and jQuery UI 1.8.18. If I use local data for the source attribute, everything works as expected. According to the documentation, a source array can be an array of string values or an array of objects:
Array: An array can be used for local data. There are two supported
formats:
An array of strings: [ "Choice1", "Choice2" ]
An array of objects with label and value properties: [ { label: "Choice1", value:
"value1" }, ... ]
Additionally, the source attribute can be a URL that responds with JSON data formatted as shown above:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
If my JSON responder returns a simple array of strings, autocomplete works exactly as it should. If, however, my JSON responder returns an array of objects formatted as above, the request is made to the URL but the dropdown list is never populated. The JavaScript console shows no errors.
The autocomplete invocation looks like this:
var source_url = '/json/codes.php?type=globalcode&cid=25';
$('.gcode').autocomplete({
minLength: 2,
source: source_url
});
The responder is written in PHP. It is just a stub until I get this problem solved:
header('Content-Type: application/json, charset=UTF-8');
...
if( !$_REQUEST['type'] || !$_REQUEST['cid'] ){
echo('[]');
return false;
}
if( $_REQUEST['type'] == 'globalcode' ){
$cid = sprintf("%d", $_REQUEST['cid']);
$stub = "[ { label: 'Label for 1234', value: '1234' }, { label: 'Label for 5678', value: '5678' } ]";
echo( $stub );
return false;
}
Again, it works with both kinds of arrays when the data is local and it works with an array of string values when the data is remote. When the data is a remote array of objects, the list is never populated and JavaScript throws no errors.
You have invalid JSON, this is never logged in the console.
JSON cannot have single quotes, use double quotes, also use JSONLint to check your JSON.
This is the valid version of your JSON:
[
{
"label": "Labelfor1234",
"value": "1234"
},
{
"label": "Labelfor5678",
"value": "5678"
}
]
You could use json_encode() instead
$stub = array(
array(
"label"=>"Labelfor1234",
"value"=>"1234"
),
array(
"label"=>"Labelfor5678",
"value"=>"5678"
)
);
echo json_encode($stub);

converting a two dimensional javascript array to JSON

i've tried a few different json methods (stringify, toJSON, and probably some totally irrelevant others out of desperation) but can't seem to figure out how to stringify this so i can pass it to a php script. i am able to create a two dimensional array that which could be represented something like this:
array(
'image'=>array(
0=>'hello.jpeg',
1=>'goodbye.jpeg',
2=>'etc.jpeg'),
'resume'=>array(
0=>'resume.doc'),
'reel'=>array(
0=>'reel.mov')
)
the array looks okay when i print it to console using this dump function. i tried figuring out how to get this to work with objects because i thought i read something that said objects were already JSON friendly, but since i'm not super familiar with javascript i was pretty much floundering about.
edit: some more details... the declaration of my array (when i had it working) was something like this, although i may have messed up:
var fileArray = [];
fileArray['image'] = [];
fileArray['resume'] = [];
fileArray['reel'] = [];
var type;
var name;
var divs = $("#upload-container").children('div');
$.each(divs, function() {
type = $(this).attr('id');
name = $(this).html();
fileArray[type].push(name);
});
The object for that array structure might look like this in JavaScript:
var objects =
[
{
'image': [
{ '0': 'hello.jpeg' },
{ '1': 'goodbye.jpeg' },
{ '2': 'etc.jpeg' }
]
},
{
'resume': [
{ '0': 'resume.doc' }
]
},
{
'reel': [
{ '0': 'reel.mov' }
]
}
]
So now you've got an array of three objects, each of which contains a property (image, resume, reel) that is another array of objects with basically key:value pairs ('0':'hello.jpeg'). Maybe you could simplify it by not bothering to use the indexes:
var objects =
[
{
'image': [ 'hello.jpeg', 'goodbye.jpeg', 'etc.jpeg' ]
},
{
'resume': [ 'resume.doc' ],
},
{
'reel': [ 'reel.mov' ]
}
]
Then you can use JSON.stringify(objects) to pass to your PHP action.
Your sample expected output on the PHP side has an associative array containing numeric arrays. JavaScript arrays have numeric indexes: if you want strings as keys use a plain object rather than an array because JavaScript objects act like the associative arrays you are thinking of from PHP. The corresponding JavaScript object should look like this:
var fileArray = {
'image' : [ 'hello.jpeg',
'goodbye.jpeg',
'etc.jpeg'],
'resume' : [ 'resume.doc' ],
'reel' : [ 'reel.mov' ]
};
In the arrays defined with square brackets the numeric indexes are implied. Note that fileArray is defined with curly braces not square brackets and so is not an array (in spite of its name). This still allows you to use the fileArray['image'] = ... syntax if you want to set the properties one at a time:
var fileArray = {}; // an object, not an array
fileArray['image'] = [];
fileArray['resume'] = [];
fileArray['reel'] = [];
Note that the curly brackets in the initial declaration make it an object but properties are still accessed with square bracket syntax.
The way you were defining fileArray as a JavaScript array with square brackets still allows you to add string-based key properties because arrays are objects, but JSON stringify routines may ignore those properties and only serialise the numerically indexed properties.

iterate through json and access two dimensions deep

I'm returning rows from a mysql database in php and then making an array of all these rows and then json encoding this. I am then trying to turn that json into autocomplete for jquery, not that relavent. The issue I have is that once I have it in json, there is no defining the rows. How do I access the same json.id that is in every "row" returned in json? here is a sample json object I'm using
[{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}]
I do I access the first id, or the second one?, etc
Here's some sample code showing how to iterate over your data:
var data = [{"id":"95833","fname":"john","lname":"walker","email":"john.walker#john.edu","major":"UNDECID ED","year":"14","gender":"0","created":"0000-00-00 00:00:00"}, {"id":"95834","fname":"joseph","lname":"train","email":"jo.train#john.edu","major":"","year":" 12","gender":"0","created":"0000-00-00 00:00:00"}];
for( var i = 0; i < data.length; i ++ )
{
var item = data[i];
var thisID = item.id;
// do something clever here
}
jQuery will parse the JSON into a Javascript array of objects for you:
data[0].id // First id
data[1].id // Second id
I think, I think you're trying to access the "columns", not the rows. Incidentally, this general problem of the relation model of the a SQL database not matching the object model of most languages is called "The Impedance Mismatch", and it sucks. Your particular issue could be addressed (in jQuery) with:
$.map(data, function(n) { return n.id } );
Which will return an array containing all the id values.
If you are using jQuery 1.6 then it's very simple
// to get ['id', 'fname', 'lname', 'email', 'major', 'year', 'gender', 'created']
// you only need to map the first element of the data array and return the key.
var columnArray = $.map(data[0], function (val, k) {
return k;
});
Happy Coding :)

Accessing JSON encoded MuliDimensional array using jQuery

I have an multidimensional array
$array = array(
"Level1"=>array(
"Level11"=>array(
"level111"=>'value1',
"level112"=>'value2',
),
"Level12"=>array(
"level121"=>'value1',
"level122"=>'value2',
),
),
"Level2"=>array(
"Level21"=>array(
"level211"=>'value1',
"level212"=>'value2',
),
"Level22"=>array(
"level221"=>'value1',
"level222"=>'value2',
),
)
);
echo json_encode($array);
This encoded JSON is sent after receiving AJAX POST request using jQuery.
$.post(
'mypage.php',
{
param1: value1,
param2: value2
},
function(data) {
//Now I can access the 1st level JSON value easily like
alert(data.Level1);
// But
// I am trying to access the values like
alert(data.Level1.Level11.level112); //which is not possible
},
"json"
);
If you have understood my question, do you know how I could tackle this problem.
Ok, my guess: You use capital letters in some of your keys in PHP but not in JS. Your line should be:
data.Level1.Level11.level112
Note that it is Level1 with captial L, not level1.
DEMO

Categories