I have a PHP array that I want to pass to the jQuery function that called it. However when I tried to retrieve the value of 'lat' the way i did below, I get the error Cannot read property 'lat' of null, obviously because I dont know how to access a multidimensional JSON array. Can anyone show me how?
PHP Array
Array
(
[0] => Array
(
[price] => 1600
[bedroom] => 1
[lat] => -71.119385
[lng] => 42.373917
[distance] => 6.65195429565453
)
[1] => Array
(
[price] => 1800
[bedroom] => 1
[lat] => -71.104248
[lng] => 42.368172
[distance] => 4.957829810472103
)
}
This gets encoded into
JSON
[{"price":"1600","bedroom":"1","lat":"-71.119385","lng":"42.373917","distance":"6.65195429565453"},{"price":"1800","bedroom":"1","lat":"-71.104248","lng":"42.368172","distance":"4.957829810472103"}]
jQuery
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
$("#result").html(json.lat);
console.log(json.lat);
});
});
});
json is an array, so it won't have the property lat.
Try:
json[0].lat
To get the first object's lat property, for example.
$.getJSON('index.php/main/get_places', {search_location: search_location}, function(json){
$.each(json, function(key, val) {
console.log(val.lat);
});
});
Your json is returning as an array of objects, so you need to reference the scalar first. Change your references to json.lat into json[0].lat.
Then, if you need to you can write a for loop and reference it as json[i].lat, assuming that i is your iterator variable.
json is an array of objects, just as it is in your php code.
So there are two lat values:
json[0].lat // and
json[1].lat
The json variable itself is null, as stated by the error message. All the answers about accessing subindexes of json or iterating over it like an array will fail because of this.
Look at the documentation for jQuery's getJSON and parseJSON. getJSON passes the server's response through parseJSON to convert it to a Javascript object. parseJSON returns null "if you pass in nothing, an empty string, null, or undefined."
I would use your browser's debugger to look at the raw http response from the server, because that is likely the culprit.
http://api.jquery.com/jQuery.getJSON/
http://api.jquery.com/jQuery.parseJSON/
Related
I'm trying to print a value from a object array, but I'm facing some problems. I want to echo in php the value of [title] but i am not getting it!
stdClass Object (
[result] => success
[records] => stdClass Object (
[500272328] => stdClass Object (
[nif] => 500272328
[pc4] => 2775
[pc3] => 372
[seo_url] => solnave-restaurantes-e-alimentacao-s-a
[title] => Solnave - Restaurantes e Alimentação S.a
[city] => Cascais
[racius] => http://www.racius.com/solnave-restaurantes-e-alimentacao-s-a/
[portugalio] => http://www.portugalio.com/solnave-restaurantes-e-alimentacao-sa-2/
)
)
)
How can i retrieve?
Thank you!
I am assuming you are calling json_decode to decode the JSON string.
You should call it as json_decode($thestring_to_be_decoded, true). This will convert the objects to associative arrays and you will be able to access the title field.
Your stdClass is a PHP object or a Javascript encoded object?
It seems a PHP, so to echo title element you must navigate at there:
echo $yourobjarray->records->500272328->title;
or
echo $yourobjarray->records->500272328['title'];
(not evident in your question)
But to echo into <script> section of a HTML page,
<script> ...
var x='<?= $yourobjarray->records->500272328['title'];?>';
...</script>
and, if a AJAX context, to JSON response you need
echo json_encode($x);
where $x is your array or the title string, or what you want.
You can make use of a foreach construct to loop through your JSON decoded object array or If you want to print individual elements you can simply do like this.
echo $yourobjarray->result; //"prints" success
I am having an issue with PHP to JavaScript and then sorting. I have the following JS script
function sortby(param, data) {
switch (param) {
case "aplha":
console.log(data);
data.sort();
break;
}
}
The array this is passing is through json_encode and the array looks like so
Array ( [0] => Array ( [Name] => 123456 [Clean_Name] => 123456 [CreateDate] => 1372479841 ) [1] => Array ( [Name] => 123456 [Clean_Name] => 123456 [CreateDate] => 1372479841 ) )
However I get the above error when I try to pass it as data.sort(). Any ideas?
PHP arrays aren't js arrays, but JSON objects, so you can't have and array on your js code. However, there's a workaround, refer to this answer for more info.
Cheers
I think i found my issue however i dont know how to fix it. when i pass the variable with json_encode to the javascript function it passing it as a string so data[0] == [ ... what am i missing here
ALRIGHT wow i found my issue i am so sorry guys i am so dumb
<script>sortby('aplha', '<?=json_encode($teamList);?>');</script>
That was my old this is my new
<script>sortby('aplha', <?=json_encode($teamList);?>);</script>
It was the ' that was passing it incorrectly ... it works fine now I hit my desk so hard ...
Array
(
[0] => Array
(
[price_id] => 1
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 2
[price] => 90.0000
)
[1] => Array
(
[price_id] => 2
[website_id] => 0
[all_groups] => 1
[cust_group] => 32000
[price_qty] => 5
[price] => 80.0000
)
.......
)
the array element maybe one or two or more, if i want to pass [price_qty] and [price] value to the jquery code. how should i do? could someone make me an example. thank you
you should consider using JSON strings in order to use key based arrays in JavaScript.
http://php.net/json
json_encode your php arrays to json
Use json_encode to convert your php array to json :)
A possible solution is to convert php array structures into JSON before passing the data to the client.
Have a look at php json.
And also have a look at this post.
Try with Json:
json_encode($array);
This will encode the array into a json object, that is friendly with javascript (and Jquery).
If you are passing it through an ajax request just echo it in the php and return that as response.
If it's in the same script you could do:
$object = json_encode($array);
echo "var myObject = $object;";
And for accessing the information in javascript/jquery you would do:
alert(myObject[0].price_id);
you use myObject[0] to access positions as in php arrays, and myObject[0].name to access what would be associative array key in an array.
For more information visit json documentation page
Well while you ask to move from [php]array to [javascript]array, this is how to. You should ue json_encode how the previous answer said, but in you javascript you can use the following code to convert a json into an array:
function json2Array = function(json){
var a = [];
for(var o in json){
a.push(json[o]);
}
return a;
}
var myArray = json2Array(youPhpJsonEncode);
and you will have your array in javascript
After a series of attempts working on json, now I have another challenge - How can post this type of json array,
[{"success":true,"filename":"agard.jpg"}]
jquery.post,
$.post("process.php", json ,function(xml){
});
So I can get this array in process.php using print_r($_POST):
Array
(
[success] => true
[filename] => agard.jpg
)
You need to pass an object not an array, you can put the array in your object though.
{"0":[{"success":true,"filename":"agard.jpg"}]}
Sorry for asking a basic question like this but I've been reading on this for a few hours now and the examples aren't making sense to me in context of the way my array is.. I have been able to pass this from my server side (cakephp) to the javascript (I'm using jquery) but after that, I am lost as to how to make use of the data.. I tried just showing it using an alert, but it gives output like "object Object" and thats all..
This is an example array that I have:
Array (
[0] => Array ( [Uiemail] => Array ( [uiemail_id] => 2 [divid] => upd1 [width] => 200 [height] => 200 [leftpos] => 122 [toppos] => 122 [cssgroup] => 1 [colortop] => [colorbottom] => [colorborder] => [borderwidth] => [zindex] => ) )
[1] => Array ( [Uiemail] => Array ( [uiemail_id] => 3 [divid] => upd2 [width] => 200 [height] => 200 [leftpos] => 333 [toppos] => 444 [cssgroup] => 1 [colortop] => [colorbottom] => [colorborder] => [borderwidth] => [zindex] => ) )
[2] => Array ( [Uiemail] => Array ( [uiemail_id] => 4 [divid] => upd3 [width] => 200 [height] => 200 [leftpos] => 555 [toppos] => 466 [cssgroup] => 1 [colortop] => [colorbottom] => [colorborder] => [borderwidth] => [zindex] => ) )
)
EDIT:
The array is the way it is as its the output from a Cakephp database GET (cakephp's equivalent of this).
It has 3 arrays, the first is the "parent array" and contains the [1], [2], [3] which are like an auto-increment ID for the 2nd tier arrays.
The 2nd tier has an array that holds the 3rd, this second doesn't really contain any data other than the 3rd array (its done like this by cakephp since its representing the database table)
So, the 3rd tier array has all the data that I need, however I also would want to use the first tier ID
IN PHP A INDIVIDUAL PIECE OF DATA FROM THIS ARRAY IS ACCESSED AS SUCH:
$arrayline = [0]['Uiemail']['toppos'];
Here is some javascript I tried that didn't work (json is array name):
$(json).each(function() {
alert(this.text)
});
});
Thanks for any advice, its just that my array is a nested array (as its from a database call) and it seems most examples don't go this deep which is leading me to confusion.
An 'associative array' in PHP (i.e. with meaningful keys like your 'uiemail_id' will become an object in JSON notation. Even an array that is not exactly 0-indexed & continuous will also become one. (i.e. an array with keys 0,1,2 will result in an array, keys 1,2,3 or 0,2,3 will result in an object.
If you access a value in PHP like this:
$arrayline = $array[0]['Uiemail']['toppos'];
The access on the resulting structure in js would be:
arrayline = jsonvar[0].Uiemail.toppos;
Enabing firebug in firefox, with breakpoints, lets you easily inspect any variable available at that moment at your leisure, which makes it a far easier to debug then the usual default PHP way of just dumping variable notation to stdout (i.e. printr / var_dump's).
Try this:
$.each(json, function(index, element){
alert(element);
});
if json is your javascript object which (hopefully) already was parsed as json, you can't call the jQuery constructor function on it and expect it to work like this.
Use the $.each() helper function to iterate over an object with jQuery.
If you still got [object Object] as alert, it's because those sub elements are Arrays or real Objects themself, so you need to dig deeper. Good help is FireBug and console.dir()
Reference: $.each()
I don't really understand your array notation...but my guess is that the representation in json/javascript would be:
[
[[2, 'udp1', 200, 200, 122, ....]],
[[3, 'udp2', 200, 200, 333, ....]],
[[4, 'udp3', 200, 200, 555, ....]]
]
When you pass an array in json, the 'index names' aren't passed.
If this is the structure, then something like this might get something:
$.each(json, function(index, element){
$.each(element, function(index, sub){
alert(sub);
});
});
You have to use jQuery.each() for that.