Adding MySQL requests to JS Code from JSFiddle - javascript

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.

Related

How to submit a form and execute javascript simultaneously

As a follow-up to my last question, I have run into another problem. I am making a project on google homepage replica. The aim is to show search results the same as google and store the search history on a database. To show results, I have used this javascript:-
const q = document.getElementById('form_search');
const google = 'https://www.google.com/search?q=';
const site = '';
function google_search(event) {
event.preventDefault();
const url = google + site + '+' + q.value;
const win = window.open(url, '_self');
win.focus();
}
document.getElementById("s-btn").addEventListener("click", google_search)
To create my form, I have used the following HTML code:-
<form method="POST" name="form_search" action="form.php">
<input type="text" id="form_search" name="form_search" placeholder="Search Google or type URL">
The terms from the search bar are to be sent to a PHP file with the post method. I have 2 buttons. Let's name them button1 and button2. The javascript uses the id of button1 while button2 has no javascript and is simply a submit button.
The problem is that when I search using button1, the search results show up but no data is added to my database. But when I search using button2, no results show up( obviously because there is no js for it) but the search term is added to my database. If I reverse the id in javascript, the outcome is also reversed. I need help with making sure that when I search with button1, it shows results and also saves the data in the database. If you need additional code, I will provide it. Please keep your answers limited to javascript, PHP, or HTML solutions. I have no experience with Ajax and JQuery. Any help is appreciated.
Tony since there is limited code available so go with what you had stated in your question.
It is a design pattern issue not so much as so the event issue.
Copy pasting from Wikipedia "software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into source or machine code. Rather, it is a description or template for how to solve a problem that can be used in many different situations. Design patterns are formalized best practices that the programmer can use to solve common problems when designing an application or system."
So here is how things play out at present;
forms gets submitted to specific URL i.e. based on action attribute
Requested page gets Query sting in php and lets you play around with it
then from there on .....
3. either you get results from database and return response
4. or you put search request into database and return success response
Problem statement
if its 3 then search request is not added to database if its 4 then results in response to search request are not returned.
Solution
you need to combine both 3 and 4 in to one processing block and will always run regardless of the search query is.
So our design pattern could use mysql transaction so whole bunch of queries would run a single operation example
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
slightly more safe version
try {
$db->beginTransaction(); // we tell tell mysql we will multiple queries as single operation
$db->query('insert query');
$results= $db->query('search query');
$db->commit(); // if we have reached to this end it means all went fine no error etc so we commit which will make database record insert query into database. If there were errors then mysql wont record data.
if($results) {echo $results;} else {echo 'opps no result found';}
} catch (\Throwable $e) {
// An exception has been thrown must rollback the transaction
$db->rollback();
echo 'oho server could not process request';
}
We have effectively combined two query operation into one always recording into database and always searching in database.

Scrape CSV data to SQL table using PHP, LOAD DATA from URL with Javascript object, (beginner)

(I'm learning and not a pro, so please excuse any faux pas)
I am aware that the PHP, LOAD DATA function may be what I need, but I can't get to the file behind the Java Object.
I am trying to update a SQL table, i.e. overwrite matching dates, with data from a CSV file from Javascript buttons on one of these websites:
-"Download Data" from https://www.investing.com/rates-bonds/us-10-yr-t-note-historical-data (adjusting dates would be ideal)
-"Download Range" from https://www.barchart.com/futures/quotes/Znh18/price-history/historical
-"Download Spreadsheet" from http://quotes.wsj.com/bond/BX/TMUBMUSD10Y/historical-prices
The data looks something like this
Time,Open,High,Low,"Last Price",Change,Volume,"Open Interest"
02/08/18,121.0781,121.25,120.5313,120.8906,-0.10939999999999,2938115,0
02/07/18,121.2031,121.6094,120.8594,121,-0.48439999999999,2201308,3569670
I have used the http://simplehtmldom.sourceforge.net/ utility to extract individual pieces of data, but that seems laborious if a file exists.
e.g. currently this is my code for finding table data on the WSJ page using the file_get_html() function:
...
// Finds the last cash price
foreach($html->find('span[id=price_quote_val]') as $e){
echo str_replace("/32.","",str_replace(" ",".",$e->plaintext)). ' last cash price<br>';
$field='Last';
$value=str_replace("/32.","",str_replace(" ",".",$e->plaintext));
include('table_update.php');
}
....
Thanks!
Chris
I have read other posts, including:
Save CSV files into mysql database
Importing CSV data using PHP/MySQL

Scraping a webpage with python to get onclick values

First of all I have to say: be patient with me because I am not familiar with the argument that I am going to illustrate you.
I'd like to download the intraday historical values of some equities on Frankfurt Boerse website. Let me take this equity for example: http://www.boerse-frankfurt.de/en/equities/adidas+ag+DE000A1EWWW0/price+turnover+history/tick+data#page=1
As you can see there are two options: trades on Frankfurt and trades on Xetra. I'd love to download the latters. I tried to scrape the data but my knowledge of python is very poor.
How can I 'select' the desired onclick option?
Thanks in advance for your replies. Regards
Ps: For your information, I noted the following fact inspecting the Xetra element: it changes value when I move on to next page and if I come back the value is again different. Here an example: first time on page 1 I got
a onclick="d39081344_fkt_set_par('6');d39081344_fkt_set_active(this);" class="brs_d39081344_li current last"
, then I moved on to page 2 and I got
a onclick="d51109535_fkt_set_par('6');d51109535_fkt_set_active(this);" class="brs_d51109535_li current last" and coming back to page 1 I got a onclick="d96086211_fkt_set_par('6');d96086211_fkt_set_active(this);" class="brs_d96086211_li current last"
The trick is to look at what calls are made when you navigate through the pages. Your browser's network analysis tool is invaluable for this. When I go from page to page, a POST is made to 'http://www.boerse-frankfurt.de/en/parts/boxes/history/_tickdata_full.m with data about the request.
Then the goal is to replicate and loop the requests using python. Here is code to get you started:
import requests
r = requests.post('http://www.boerse-frankfurt.de/en/parts/boxes/history/_tickdata_full.m', data={'component_id':'PREKOP97077bf9dec39f14320bf9d40b636c7c589', 'page':"3", 'page_size':'50', 'boerse_id':'6', 'titel':'Tick-Data', 'lang':'en', 'text':'LOcbaec84ecad1b94ad2fd257897c87361', 'items_per_page':'50', 'template':'0', 'pages_total':'50', 'use_external_secu':'1', 'item_count':'2473', 'include_url':'/parts/boxes/history/_tickdata_full.m', 'ag':'291', 'secu':'291', })
print r.text #here is your data of interest, it still needs to be parsed
That is the general idea. You would then put that in a loop, adding one to the page parameter each time.

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>

Plotting a graph with flot using sqlite db information

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/

Categories