I have my data in mysql. I am using PDO to pull data with php then using json_encode to convert to js. When i use following scenario, i always get output NaN and if i use static array it works. So I am guessing it's either wrong json format or something with php.
This works if I set values for array smoothly: codepen: http://codepen.io/pghiran/pen/QEvRjW
Dynamic (pulling data from db and storing in array, doesn't work. My code for doing this:
PHP
$exchangeRates = array();
$sql = 'SELECT * FROM exchange';
try {
$stmt = $conn->prepare($sql);
$stmt->execute();
for ($i=0; $row=$stmt->fetch();$i++){
$exchangeRates[] = array($row['rs3'],$row['07'],$row['deadman'],$row['currency']);
}
}catch(exception $e){
return $e;
}
var_dump($exchangeRates);
var_dump displays: array(1) { [0]=> array(4) { [0]=> string(3) "0.5" [1]=> string(3) "1.5" [2]=> string(3) "3.5" [3]=> string(1) "$" } }
JS/Jquery:
var amount = $('#amount'),
goldtype = $('#goldtype'),
exchange= <?php echo json_encode($exchangeRates);?>,
price = $('#price');
console.log(exchange);
goldtype.change(function () {
var exchangeIndex = $("select[name='goldtype'] option:selected").index();
price.val(amount.val() * exchange[exchangeIndex]);
})
console.log(exchange) displays:
[Array[4]]
0
:
Array[4]
0
:
"0.5"
1
:
"1.5"
2
:
"3.5"
3
:
"$"
length
:
4
json_encodeit.. just add[0]to your calling of the data when multiplying it toamount.val()e.g.price.val(amount.val() * exchange[0][exchangeIndex]);exchange= <?php echo $exchangeRates;?>it is already in an array format similar to the hard coded one you show on codepen.console.log(exchange[0][0] + ' ' + exchange[0][1] + ' ' + exchange[0][2] + ' ' + exchange[0][3]);and check it's collecting the correct data from the array.