I am building a currency converter app for my school project and at the moment I am trying to get data from the database into a .js
file. The exact goal is to get data from the database and save it into an array within a .js
file.
As far as I know there is no way to get data from the database directly into a JavaScript file, so I am trying to make use of JQuery and PHP combination as pointed out in this thread.
I have a database called 'currencies'
which has six columns: id, basecur1, basecur2, basecur3, basecur4, basecur5
.
id
field is for user id, and basecur_
fields are for storing user's prefered currencies and can only contain three characters of a currency code (like USD
or GBP
) or be empty. I need to get a result looking like const array_name = ["EUR", "GBP", "USD"];
Please note that I am using CodeIgniter PHP framework for back-end.
In this file query.php
I am trying to create an array from the data fetched from the database and echo it:
<?php
$current_user = $this->session->user_id;
$query = $this->db->get_where('currencies', array('id' => $current_user));
$row1 = $query->row();
$base_currencies = array($row1->basecur1, $row1->basecur2, $row1->basecur3, $row1->basecur4, $row1->basecur5);
$post_data = json_encode($base_currencies);
echo $post_data;
?>
Unfortunately, I don't have deep understanding of JavaScript, so I can't really say what's wrong with this JS code, which is taken from the thread mentioned above, but it doesn't really work for me:
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
async: false,
success: function(data) {
result = JSON.stringify(data);
}
});
return result;
}
});
var array_name = $.getValues("query.php");
Any help will be much appreciated.