Plotting a graph with flot using sqlite db information - javascript

I'm trying to read data from the internal sqlite database, and plot a graph using flot based
on this data.
I have an activity which inserts data into the db, accesses the db and even returns an
array with the desired data.
I also have an activity which creates a webview, and adds a javascript interface to a class
so that I can use flot and javascript to create the graph.
Both of these activities function perfectly individually but my problem lies in getting the
array of db data to a javascript interface class so that it can be accessed from javascript.
I've tried to use "Bundle.getExtra()"..etc.. to send the array from one activity to the other, but when
I go to retrieve it in the js class it can only be retrieved from the onCreate method, and hence
cannot be accessed from a javascript interface.
This is driving me crazy, any help at all would be much appreciated.
Thank you,
D

Note sure what you want, but here i go:
If you want to fill out some data from a query you could do it quick and easy by doing something like this in php:
<?php
foreach($res in $query )
{
echo "var d1 = [[0, ". $res['xxx'] ."], [1, ". $res['yyy'] ."], [2, ". $res['zzz'] ."]];";
}
?>
where you normally fill in the datavalues. You might even use Ajax, and then i recomend reading http://api.jquery.com/jQuery.get/

Related

get only specific element of a JSON database stored in server by url request

my website relies on a database which is a big JSON file like this:
var myjsonData =
[ {
"ID": 0,
"name": "Henry",
"surname": "McLarry",
"...": "...",
}]
I do generate this data every month at high cost to me, therefore I would like to avoid calling it straight in my html <head>, because this will allow any user to download the full database in no time.
I would like to build a "something" that can only call specific items from the json file (just the only one I want to show) without "exposing" the full .json onto client side.
today I use the call
var myvar= myjsonData.ID.Name
to get "Henry" into myvar, I would like to build something like
var myvar = mycallfunction(ID,Name)
I did try with PHP as intermediary but the ajax calls from javacript doesn't allow me to fetch the data.
Can I use JQuery with the JSON Url to get only the item I need?
What you can do is parse your json for an object. So you can get any value you want from json.
Example:
var myjsonData = '{"ID": 0,"name": "Henry","surname": "McLarry"}';
obj = JSON.parse(myjsonData);
console.log(myjsonData.ID); //print the id
console.log(myjsonData.name); //print the name
console.log(myjsonData.surname); //print the surname
So you have a NoSQL Database which has only one kind of Document that is the full JSON element you use in your website. In that scenario you have three options:
Depending on the NoSQL Database you're using you can limit the fields which will be returned(I.e: For MongoDB you can look here: https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/)
Change the way you store you data into more modular documents and make the logic to connect them in you application. So instead of one big document you'll have modular ones as Users, Products, Transactions and etc and you can use your application to query them individually.
Build a Server Side logic as an API to deal with your data and provide only what you need, so the API(Which can be node.js, php, or any you may like) will get the full JSON it`s endpoints will only the data you want. For example: myapi.com/getUser, myapi.com/getProducts and so on.
If you're able to provide more info on the technologies you're using that would help us. Hope that helped :).

How to properly unpack data from PHP array encoded as JSON from a JavaScript file

I have been doing searches for hours upon hours and have tried different snippets of codes and techniques and I simply cannot get any of them to work. I have done research, I am simply a very inexperienced developer trying to learn as I go.
My ultimate goal: Have a live-updating graph of test results data pulled from a MySQL database and rendered using Chart.JS library.
What I have done so far:
I have an HTML file with embedded JavaScript and calls to AJAX function to auto-refresh page every 5 minutes (this has been tested and works).
I have a PHP file which opens a PDO connection to a local MySQL database, runs 3 selection queries, and stores the results into 3 PHP arrays. (I have iterated through the arrays and echoed the results and the data is good).
I have then stored the data inside these PHP arrays into a JSON object using json_encode()
e.g.
$totalTestsPassedArray = array();
$sql = "SELECT totalTestsPassed FROM execution ORDER BY lastDate";
$query = $conn->prepare($sql);
$query->execute(array(':totalTestsPassed' => $totalTestsPassed));
while($row = $query->fetch()){
array_push($totalTestsPassedArray, $row['totalTestsPassed']);
}
$json_totalTestsPassedArray = json_encode($totalTestsPassedArray); //pack data into JSON object
echo $json_totalTestsPassedArray; // for accessibility by AJAX
foreach ($totalTestsPassedArray as $item){ //print out contents of array
echo $item . '<br>';
}
I read that one method to consume this JSON data is to use jQuery's $.getJSON method, and in order to use it, I must 'echo' out the results of my json_encoded object. I realize I am printing the results twice. The echo $json_totalTestsPassedArray is for the aforementioned purpose.
I have included the path of this PHP file in my HTML file from #1 using <?php require '../file_name.php';?>
I have tried several ways of unpacking this JSON encoded object packed with my database data: using AJAX requests, making a new array in the HTML and then flooding it with the JSON object using $.getJSON, and some other things people have suggested to do on various documents online, all met with failure.
Could someone please tell me the proper way to do what I am trying to do? I have a PHP file with an array of data, and I would like to pass that array of data into a dataset for use by Chart.JS to populate a graph and then draw it to the canvas and display my results.
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data : [DATA FROM MY PHP ARRAY IN ANOTHER FILE WOULD GO HERE...]
}
Again, please forgive my ignorance. I have tried my best to figure out the solution on my own and would really appreciate some guidance. It's my first time using these tools. I thought it would be as simple as:
Query DB using PHP script
Store results into array
Pack into JSON object (the goal being to transfer data from PHP to JS file)
Unpack JSON object in JavaScript
Load unpacked data into my JavaScript array
In php print only json and set header content type to application/json then your XHR response will contain javascript object with your data. There is no need for any json parsing.

Cleanly passing large JSON array from Laravel to Javascript

So in my controller logic, I build up a large array of data, which I json_encode into a variable which is passed to my view. However, I want this data to be sortable on the client side using JavaScipt--I don't think the details of how the sorting is done are relevant but I'm curious what the best way is to get my array from PHP to Javascript. Currently, I'm thinking of just having a tag in my html like
<script type="text/javascript">var jsonData = <?php echo $myData ?>; </script>
where myData is the encoded array I made in PHP, and then jsonData is available for me to use anywhere else.
However, this would mean the entire ugly array would show up in the source code of my page. This isn't a security concern or anything, but I feel that there must be a better way to do this that's not quite as "ugly".
Any advice is appreciated.
You have two options.
If you don't want 'ugly' HTML source, you can query your application with ajax and have your json array be stored in a variable. This can be accomplished with a simple route and controller method.
In your routes.php
Route::get('api/myData',array('as'=>'api.myData','uses'=>'MyController#getMyData'));
In your MyController.php
public function getMyData() {
return whateverYouWant();
}
You can then do an ajax request to route('api.myData')
The route method is a global function which is available in your view. It will take the named route, api.myData and generate a URL for it.
The other option is as you described, passing the array to your view.

Using PHP in a Javascript music player playlist

I've been working on a music player that's quite simple and to add music to it you would have to upload it to Dropbox and then manually edit the file (in this case index.php) where the playlist is held.The player then plays the links.
But what I've done is made a file which inserts value through mysql into the database.Two columns:
songname, url
Index.php:
`$(document).ready(function(){
var myPlaylist = new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_N",
cssSelectorAncestor: "#jp_container_N"
}, [
{
title:"C O O L",
artist:"Le Youth",
mp3:"this is where the link must sit",
},`
How can I implement PHP query that selects the name and the link from database into that part of javascript code?
I'm sorry if there's some unclear things for you, please ask I will try to make everything clear.
PHP is a server-side language and it dies after it renders the page. So, you have two good options here.
First one is to grab all the links/names from the database, and then echo that into a JS object (using JSON seems the easiest way to handle the conversion), and then just call the link you need from that JS object. You can build the whole title/artist/mp3 object using PHP and be good to go. It should look something like this:
var mySonglist = <?php echo json_encode($databaseData) ?>;
The other option would require making AJAX calls to retrieve the link of the selected mp3. Although this might seem closer to what you're asking, due to its speed (it makes another server call), I'd suggest you do it only if you have a really, really huge number of songs at once.
So, the bottom line is: extend your PHP functionality to grab everything you need from the database, all the data, and then put that data into a JS variable which you will use to configure your player.
I am not sure that you can do db queries inside your script functions, But Do the queries outside the function and pass the php variables as arguments for the function. Below is an example.
<?php
$var="Select query here";
$name=$var[0]; $url = $var[1];
?>
<script>
play('$name','$url');
function play(name,url);
{
//your code goes here..
}
</script>

Adding MySQL requests to JS Code from JSFiddle

First and foremost, I want to say how amazing this community is. I've been reading and using this place for a bit now to get answers to a plethora of questions.
I'm currently working on building a student list (never really built a system before) system for our company using Bootstrap 3. I've got the meat of it worked out and have found this awesome JSFiddle by user Mils (many thanks) that does what I need it to in terms of adjusting data dynamically, which would be ideal for what we want.
http://jsfiddle.net/NfPcH/645/
My question is: how can I alter this so that it pulls data from a MySQL database I've created, and how do I alter it so that when adding/editing a row, it writes it to the db? I have a students.php page I created that pulls in the information as such:
// Prepare SQL Query
$STM = $db->prepare("SELECT `student_firstname`, `student_lastname`, `student_class`, `year` FROM students ORDER BY student_firstname");
// For executing prepared statement
$STM->execute();
// Fetch records
$STMrecords = $STM->fetchAll();
foreach($STMrecords as $row)
{
echo"<tr>";
echo"<td><a href='#' id='student-firstname' data-type='text' data-pk=".$row['student_firstname']."</td>";
echo"<td>".$row['student_lastname']."</td>";
echo"<td>".$row['student_class']."</td>";
echo"<td>".$row['year']."</td>";
echo"</tr>";
}
But this doesn't go hand-in-hand with the aforementioned JSFiddle, as it only posts the data on the page.
Thanks, everyone!
You need to redirect the get request in the JSFiddle to you php script. And the php script needs to return something on the expected format.
At the end of the fiddle there is a couple of mocks, there you can see how the output from the php script should be formatted.

Categories