View Full Version : Return an array of data
NancyJ
01-12-2008, 01:59 AM
I need to request a set of distances from a php script and get them into a javascript array where id=>distance (id being numerical, I know javascript doesn't do associative arrays but I'm hoping it can no non-sequential numerical indexes) in the simplest way possible.
If it helps I'm using prototype for my ajax calls.
shyam
01-12-2008, 03:54 AM
I need to request a set of distances from a php script and get them into a javascript array where id=>distance (id being numerical, I know javascript doesn't do associative arrays but I'm hoping it can no non-sequential numerical indexes) in the simplest way possible.
If it helps I'm using prototype for my ajax calls.
how did u get that wrong impression? javascript does have associative arrays
var hash = { name: 'jack', spouse: 'jill', location:'hill'};
alert(hash['name']); // gives jack
in ur case
var hash = {1:34.3, 2:6.5};
if yoiu hae php 5.2 or newer, or the JSON extension installed then json_encode() will do what you want. If you want the php to have gaps, then you'll want it to be a js object, ({}s), and then prototype will let you access it by using xhr.responseJSON in your onComplete function, instead of responseText.
If you subsequently need to iterate the object, then things will be made easier if you use the $H function, that lets you use .each() and friends, and access the keys as well as values quite simply.
NancyJ
01-13-2008, 01:56 PM
if yoiu hae php 5.2 or newer, or the JSON extension installed then json_encode() will do what you want. If you want the php to have gaps, then you'll want it to be a js object, ({}s), and then prototype will let you access it by using xhr.responseJSON in your onComplete function, instead of responseText.
If you subsequently need to iterate the object, then things will be made easier if you use the $H function, that lets you use .each() and friends, and access the keys as well as values quite simply.
Thanks GJay, that sounds perfect.
NancyJ
01-13-2008, 11:37 PM
I gave it a try
function changePort(id)
{
new Ajax.Request('/calculator/get_distances/'+id,
{
onSuccess: function(transport)
{
distances = transport.responseJSON;
recalculate();
}
});
}
The php looks ok http://tradersoftheburningsea.com/calculator/get_distances/4
and firebug says thats coming through ok but when I alert distances I get 'null'
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.