colorArray will be an array of the form
[2.339, 3.195, 6.537, 2.614, 2.614, 1.759]
according to the php json_encode()
documentation.
I've put together a Working Demo to demonstrate how to handle data returned in a JSON string as an array. add /edit to the URL to see the code.
Code from the demo
$(function() {
$('button').click(function() {
// the URL is just another page on jsbin.com that contains
// this string - ["2.339","3.195","6.537","2.614","2.614","1.759"]
$.getJSON('http://jsbin.com/amibo', function(data) {
$.each(data, function(i,v) {
$('<div>').text(v).appendTo('body');
});
});
});
});
Note that in your example, colorArray
is declared locally inside the function that executes when the AJAX request has completed and therefore will not be available outside of that scope. You can either use a higher scoped variable to capture the returned data or perform your iteration inside of the callback function.
EDIT:
I've looked at your code here and you would need something like this
$('#quantity').change(function() {
var qty = $('option:selected', this).val();
switch (qty) {
case '250':
$.getJSON('scripts/jsondata.php',function(data) {
// call the new updateOptionLabels function
updateOptionLabels(qty, data);
// I'm not sure if you needed this part as it seems to
// essentially duplicate the new updateOptionLabels function
// I've commented out but I may misunderstand what you're doing
/*
$.each(data, function(i, value) {
$('#colors option').eq(i).attr('label',qty * value);
});
*/
});
break;
case '500':
// ditto, but retrieving a different array
break;
// etc...
default:
alert("Default");
break;
}
// I'd like to use that local "colorArray" variable here
function updateOptionLabels(qty, arr) {
$('#colors option').each(function(i) {
$(this).attr('label',qty * arr[i]);
});
}
});
I've introduced a new function for updating option labels. This function is scoped to the function executed when the change event is raised on <select>
with id quantity
. The variable qty
can be used inside of the callback function for the getJSON()
command in each case statement as it is declared outside of the scope of the callback function. The data
variable and the qty
are both passed into the updateOptionLabels()
function so that this code is not duplicated in each case statement. This could probably be refined earlier. I've commented out the $.each()
for the moment as it looks as though what you were trying to do with that is now taken care of by the updateOptionLabels()
function.
I would suggest taking a look at Doug Crockford's excellent Survey of the JavaScript Programming Language, particularly the section on Functions. Also take a look at Mozilla's excellent Core JavaScript 1.5 reference material. Here's the section on Functions and function scope