Filtering using ajax - javascript

I'm a FileMaker programmer trying to port a database across to the web using PHP their API. I've got my php page working, retrieving and displaying the correct data from my search, however I would like to filter the results on my page every time my user picks a checkbox (Apple, Microsoft etc) without hitting the submit button. I know I need to use ajax to perform this, however can I inject the ajax into this page below or am I now going to have to break down the page into various smaller files, php and js files?
Most of the samples I have found are json based, which do filtering client side. FileMaker returns an odd type array with PHP which requires further processing to get into json format. I'm ideally looking for a way to just post back the form everytime my user click on a checkbox, which I think maybe simpler if possible?
<?php require_once('../db.php');
if(isset($_REQUEST['search'][0]))
{
$find = $fm->newCompoundFindCommand('Data');
$request1 = $fm->newFindRequest('Data');
if(isset($_REQUEST['search'][1])){ $request2 = $fm->newFindRequest('Data'); }
if(isset($_REQUEST['search'][2])){ $request3 = $fm->newFindRequest('Data'); }
$request1->addFindCriterion('Company',$_REQUEST['search'][0]);
if(isset($_REQUEST['search'][1])){ $request2->addFindCriterion('Company',$_REQUEST['search'][1]); }
if(isset($_REQUEST['search'][2])){ $request3->addFindCriterion('Company',$_REQUEST['search'][2]); }
$find->add(1,$request1);
if(isset($_REQUEST['search'][1])){ $find->add(2,$request2); }
if(isset($_REQUEST['search'][2])){ $find->add(3,$request3); }
$result = $find->execute();
} else {
$request = $fm->newFindCommand('Data');
$request->addFindCriterion('Company','*');
$result = $request->execute();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<div id="filters">
<form action="data_table.php" method="post">
<input class="category" id="check1" name="search[]" type="checkbox" value="Apple">
<label for="check1">Apple</label>
<input class="category" id="check2" name="search[]" type="checkbox" value="Google">
<label for="check2">Google</label>
<input class="category" id="check3" name="search[]" type="checkbox" value="Microsoft">
<label for="check3">Microsoft</label> <input type="submit" value="Submit">
</form>
</div>
<table border="0" class="table table-striped" width="100%">
<thead>
<tr>
<th>Company</th>
</tr>
</thead><?php if(!FileMaker::isError($result)) {?>
<tbody class="searchable">
<?php foreach($result->getRecords() as $row){ ?>
<tr>
<td><?php echo $row->getField('Company'); ?></td>
</tr><?php } ?>
</tbody><?php } ?>
</table><!-- end row -->
</body>
</html>

Let me try and break down you code part.
$request->addFindCriterion('Company','*');
$result = $request->execute();
At this point you have the results after applying the query. Just encode it in json like
echo json_encode($result);
this is your api endpoints. You will be making all ajax queries over here. Move all html content to a separate file.
Now this part of code
<table border="0" class="table table-striped" width="100%">
<thead>
<tr>
<th>Company</th>
</tr>
</thead><?php if(!FileMaker::isError($result)) {?>
<tbody class="searchable">
<?php foreach($result->getRecords() as $row){ ?>
<tr>
<td><?php echo $row->getField('Company'); ?></td>
</tr><?php } ?>
</tbody><?php } ?>
</table><!-- end row -->
becomes obsolete as you might have guessed for obvious reasons. There is no $result in this file. It is just a static html. You need to make ajax request in this file to the api point we just used above. You will get the response in json. Populate it into a table. Similarly if the users has other search parameters, make ajax request with proper search and repopulate the table in javascript.
Which part is simpler ?
That purely depends on the kind of application you are building. If it is somewhat along the lines of Single Page app i would suggest javascript filtering else go for filter in api.
Remember javascript does not have proper sql database and they are implementations of localstorage so the execution might be long, but that is a tradeoff people make for persistant apps.

Related

how to get the td id in JavaScript

<table class="table" style="margin-bottom:0px!important">
<b>
<? if(!empty($channelBase['rep_ids']))
{
$s_id=$channelBase['id'];
$i=0;
$temp='';
$reps_channl=explode(",",$channelBase['rep_ids']);
foreach($reps_channl as $k)
{
$added_reps = $rep_names[$k];
if($i==0){
$temp.='<tr style="border-top:none;">';
}
$temp.="<td id='".$s_id."_".$k."' class='repclicked' style='border-top:none;'>$added_reps <a href='#' class='btn btn-xs btn-icon btn-circle ' onclick='delete_repid($k,$s_id);'><i class='fa fa-close'></i></a>
</td>";
$i++;
if($i==5)
{
$temp.='</tr>';
$i=0;
}
}
echo $temp;
}
?>
</b>
</table>
Here I have a td id with a number value. here I am getting confusion on how to get the td id in javascript. can anyone please help me.
Here is how you can get Ids of td inside table
for (let row of mytab1.rows)
{
for(let cell of row.cells)
{
console.log(cell.id)
}
}
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td id="id_1">col1 Val1</td>
<td id="id_2">col2 Val2</td>
</tr>
<tr>
<td id="id_3">col1 Val3</td>
<td id="id_4">col2 Val4</td>
</tr>
</table>
</div>
Try this,
"<td id='".$s_id."_".$k."' onclick='alert(this.id);'></td>"
You are trying to mix PHP and javascript, which you can not do. Everything in PHP is separate from javascript and the two do not have access to identifiers from each other.
The reason is this:
PHP code is completely run BEFORE the page is loaded. Once the page is loaded completely in PHP, it is then sent to the browser where the javascript acts upon whatever the result of the PHP code was.
Try this:
on a page enter:
<pre>
<?php
$a = "1";
$b = "2";
print_r($a);
print_r($b);
?>
</pre>
Now load the page and right click on the page and go to "inspect " or "view source"
you will see that the source of the page has no php code and is only
<pre>12</pre>
This is because all PHP code is processed BEFORE the page is loaded, whereas javascript is processed AFTER the page is sent to the browser.
You have to do everything involving PHP Ids first and completely separate from javascript, and likewise javascript must be completely separate from PHP.
For your case you must make a separate request in order to modify an array in PHP and then either reload the page or use AJAX to load the updated data.
The type of action you are trying to accomplish is impossible the way you are trying to do it.

How to export dynamic html table to doc file using php?

I'm new using PHP and I need a bit of help here.
I'd like to send a HTML table to another PHP file, and then, be to able to use this information (specifically I want to download this like DOC file).
I've seen a lot of information how to do it. But I haven't seen how to do without <tbody></tbody>. I have a dynamic table, so, the data is loading from an array. By the way, I'm using DataTable-jQuery to do it.
I have the following HTML code:
<form action="sectoresTable.php" method="post">
<table id="sectoresTable">
<thead>
<tr>
<th><b>#</b></th>
<th><b>Numero</b></th>
<th><b>Nombre</b></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<button type="submit" style="margin-top: 20px;">Exportar</button>
</form>
and sectoresTable.PHP:
<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=TablaSectores.doc");
echo '';
?>
By the way, to load the data into the table, I'm using the following script:
<script>
$('#sectoresTable').DataTable({
data: arraySectores
});
</script>
In general all this is working good, I download a doc file but without information (and That is right because my echo is printing nothing.).
I understand that I need to use a foreach in my HTML code? But really, I'm not sure.
try to use an api,to export dynamic html table to doc file in php
http://www.phpclasses.org/package/2763-PHP-Convert-HTML-into-Microsoft-Word-documents.html

Submitting embedded pdf in html form

I've searched in vain for days, but haven't found a solution for my problem yet.
Ideally, I would like to embed a fillable pdf form into an intranet html form for submission to the server for processing (ability to parse the field/values would be gravy, but not required). The files are all in the same domain so no cross-domain issues. I know I could add submission functionality to the pdf form itself, but 1) scripting is beyond the ability of the pdf document administrator and I don't want to take that on, 2) there are hundreds of pdf documents, 3) I need additional scripted fields/values submitted with the form, 4) I want the pdf document to be contained within the login session. So far, the server log shows all the field/values, except the PDFInput parameter which is passed, but the value is empty.
Here's what I have so far:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(uploadForm).on("submit", function(event) {
var iframe = document.getElementById('PDFObj');
var iframeDocument = [iframe.contentDocument || iframe.contentWindow.document];
var pluginData = iframeDocument;
$(this).append('<input type="file" name="PDFInput" id="PDFInput" value="' + pluginData + '" style="visibility:hidden"/>');
return true;
});
});
</script>
and
<form enctype="multipart/form-data" method="post" name='uploadForm' id='uploadForm'>
<input type='hidden' name='rm' id='rm' value='uploadFile'>
<table align='center'>
<tr>
<td align='left'>
<strong>Notes:</strong>
<br>
<textarea cols='80' rows='2' name='notes' id='notes'></textarea>
<br>
<br>
</td>
</tr>
<tr>
<td colspan=2 align='center'>
<input type='submit'>
</td>
</tr>
<tr>
<td colspan=2>
<br>
<input type='hidden' name='formid' id='formid' value='6F45B3AF-91F3-108C-D3D9-701F541B49DC'>
<iframe type='application/pdf' src="url.pl?formid=6F45B3AF-91F3-108C-D3D9-701F541B49DC.pdf" height='800' width='1000' name='PDFObj' id='PDFObj'>
</td>
</tr>
</table>
</form>
I've tried embedding it using iframe and object along with setting input type="object", but I can't get any combination to work.
Is this even possible? Is there a better approach?
As far as I know, you're not going to be able to capture the PDF data directly from HTML like that. Your best bet is going to be to add submit functionality to the PDFs, then process the resulting FDF data with a server-side script.
You will need either add Submit a Form buttons to your PDFs, or modify the existing buttons. Make sure the form action in the PDF has #FDF after the URI (eg https://example.com/process.php#FDF).
Parsing the data server side is simple. I'm not sure what server side language you are using, but here is a PHP snippet
<?php // process.php, report the data we received
echo '<h2>GET Data</h2>';
foreach( $_GET as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
echo '<h2>POST Data</h2>';
foreach( $_POST as $key => $value ) {
echo '<p>Key: '.$key.', Value: '.$value.'</p>';
}
Note that a PDF only interacts with a web server properly when viewed inside of a web browser.
I do not know of a reliable way to programmatically add submit buttons to PDFs, nor do I know of a reliable conversion method. You're between a rock and a hard place here IMHO.
More info:
http://www.w3.org/TR/WCAG20-TECHS/PDF15.html
http://etutorials.org/Linux+systems/pdf+hacks/Chapter+6.+Dynamic+PDF/Hack+74+Collect+Data+with+Online+PDF+Forms/

Creating unique URLs/Pages from MySQL DB on HTML form submit

The forums have been a huge help on this project so far. I'm looking for some guidance on the next step of my project here.
What I have is a form that feeds user submitted information into a MySQL database. This database then feeds this information to a main page displaying all of the information in the DB. What I am looking to do is add something to my form that creates a new unique URL/page when the form is submitted. I have already designed the HTML/CSS template for this page and it is designed to display only one set of information as opposed to the entire DB worth.
I am looking for some guidance as to how I can create the pages and unique URLs on the form submit. What is the best way to get this fresh information feeding from the DB immediately?
I need to somehow automatically recreate the HTML and CSS files as well on the server, this I am unfamiliar with.
EDIT: After #Jacky Cheng pointed out that this was possible without creating new versions of the HTML/CSS files I would be inclined to go about having a single HTML file on the server that is dynamic.
Thanks for any help as you guys have been great so far.
Including code for the form which I am submitting to the DB from, and the page which I will be pulling info from.
This is the form:
<?php
include_once 'post_func.inc.php';
connect();
?>
<!DOCTYPE html>
<html>
<head>
<title>Event Register</title>
</head>
<body>
<div style="text-align: center">
<h2>Event Register</h2>
<form id="eventregister"action="eventtestconnect.php" method="post">
<table style="border: 0; margin-left: auto; margin-right: auto; text-align: left">
<tr>
<td>Event Name:</td>
<td><input name="name" type="text"></td>
</tr>
<tr>
<td>Event Type:</td>
<td>
<select name="eventtype">
<?php query_eventtype() ?>
</select>
</td>
</tr>
<tr>
<tr>
<td>Venue:</td>
<td>
<select name="venue">
<?php query_venue() ?>
</select>
</td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
</div>
</body>
<?php close() ?>
</html>
This is the page I want filling with information from the DB after the form is submitted and the url is generated.
<?php
include_once 'event_func.inc.php';
connect();
?>
<html>
<head>
<title>
<?php query_eventname() ?>
</title>
<link href="eventstest.css" rel="stylesheet" type="text/css"/>
</head>
<body id="body">
<div id="maincontainer">
<div id="header">
</div>
<div id="content">
<div id="eventname">
<?php query_eventname() ?>
</div>
<div id="eventvenue">
<?php query_eventvenue() ?>
</div>
<div id="eventicon">
<?php query_eventtype() ?>
</div>
</div>
</div>
</body>
<?php close() ?>
</html>
What changes need to be made to the form in order for the url to be generated on submit and the event page to be able to jump between urls/sets of data dynamically, per-say?
Sorry for the beginner questions but this site really seems to be the best resource for these sorts of things and I haven't found anything this specific on here!
Thanks again for the help!
I am still half guessing what you want, so bear with me here.
from the description of your question, you seems to have a system that would generate an actual html file per form submit? That doesn't look good to me.
maybe try something like this :
redesign a web page that would take http GET request parameter as input (mydomain.com/display.php?id={input1}) and display only 1 set of info.
from the comments I see you have a unique id per form submit, I'd suggest avoid using it directly in the request as it'll be extremly easy to get someone else's info. Instead try somthing like MD5 encoding for that id and then sending that out to user.
so the overall system would be:
1) you'll only ever have 1 html file in your server, which will dynamically change it's content according to input, which save you a lot of space.
2) you'll have a unique & slightly more secure URL per form submit
edit:
here are some fake code to show the general idea.
form response:
$uniqueId=mysql_query("SELECT unique_id FROM my_db");
echo "http://yourdomain.com/display.php?urlid=".$uniqueId;
display.php
<?php
$uniqueId=$_GET['urlid'];
mysql_query("SELECT info_you_need FROM your_tables WHERE unique_id = $uniqueId");
?>
<html><body>your display page html here</body></html>
I guess...
You want to create product catalog page like this:
www.abc.com/Electronics/Product-Motorola-moto-g-at-Rs6999-only.html
and this will display all the product information from the database.
If the above is your case then you can use url rewrite in your project.
RewriteEngine On # Turn on the rewriting engine
RewriteRule ^Product-/?$ Product-Motorola-moto-g-at-Rs6999-only.html [NC,L] # Handle requests for "Product-"
The "RewriteRule" line is where the magic happens. The line can be broken down into 5 parts:
RewriteRule - Tells Apache that this like refers to a single RewriteRule.
^/Product/?$ - The "pattern". The server will check the URL of every request to the site to see if this pattern matches. If it does, then Apache will swap the URL of the request for the "substitution" section that follows.
Product-Motorola-moto-g-at-Rs6999-only.html - The "substitution". If the pattern above matches the request, Apache uses this URL instead of the requested URL.
[NC,L] - "Flags", that tell Apache how to apply the rule. In this case, we're using two flags. "NC", tells Apache that this rule should be case-insensitive, and "L" tells Apache not to process any more rules if this one is used.
Handle requests for "Product" - Comment explaining what the rule does (optional but recommended)
Hope this will work for you.
Feel free to ask any help.
Happy programming :)
Bear with me too. Your description is pretty bad. So if I am correct, you want form=>mysql=>confirmation
So, form should be action="process.php" method="post"
Create a process.php file where you do your validation, escaping, serializing, etc. Insert into the MySQL table. If returns true redirect (header(location:yourdomain.com)) and then on the redirected page, select the information from the Database.

Displaying data from Cryptocoin charts API with PHP

Hey Stackoverflow,
I've set myself a little project to celebrate the rise of cryptocurrency (having just been stitched up by a conventional bank myself with some incredibly 'un-Christmassy' charges, the growing use of a decentralized currency was a most welcomed revelation).
Basically, I want to be able to display data on my website from the following API:
http://www.cryptocoincharts.info/v2/api/listCoins
As (at least I believe) this will then enable me to use javascript to carry out my own exchange calculations using the data found there as a base rate, which I can then turn into a form to create as an easy to use exchange calculator.
This is what I have so far...
The example PHP from cryptocoincharts:
// fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "http://www.cryptocoincharts.info/v2/api/listCoins");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData);
// show data
echo "<pre>";
foreach ($data as $row) echo $row->id." - ".$row->name."\n";
echo "</pre>";
Javascript for the exchange calculations:
<script language="JavaScript">
<!--
function goldConverter(){
document.converter.bitcoin.value = document.converter.gold.value * 0.05019370
document.converter.litecoin.value = document.converter.gold.value * 1.56379100
document.converter.peercoin.value = document.converter.gold.value * 7.52631578
}
function bitcoinConverter(){
document.converter.gold.value = document.converter.bitcoin.value * 19.92281899
document.converter.litecoin.value = document.converter.bitcoin.value * 0.03210000
document.converter.peercoin.value = document.converter.bitcoin.value * 0.00667000
}
</script>
To further clarify my intention is to enable (more or less) real-time automated update of the exchange values using the data from cyrptocoincharts, figures listed above are there for the purpose of testing.
And here is my HTML:
<form name="converter">
<table border="0">
<tr>
<td>Gold (g): </td><td><input type="text" name="gold" onChange="goldConverter()" /></td>
</tr>
<tr>
<td>Bitcoin: </td><td><input type="text" name="bitcoin" onChange="bitcoinConverter()" /></td>
</tr>
<tr>
<td>Litecoin:</td><td><input type="text" name="litecoin" onChange="litecoinConverter()" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="Convert" /></td>
</tr>
</table>
</form>
Summary:
If anyone could either point me in the right direction (particularly regarding the API), or help me get this to work as a whole, I would really appreciate it and give credit where due, I realize I have a lot of learning to do and this is my first post on stackoverflow, so apologies if I have broken any unwritten rules.
UPDATE:
I have recently discovered money.js which potentially solves my problem, and I am currently attempting to change the data source from OpenExchange Rates API to Cryptocoin Charts API.
UPDATE 2.0:
Now using simple_html_dom.php to scrape the HTML page as seems most straight forward method, however I am receiving the following errors:
Warning: include_once(simple_html_dom.php) [function.include-once]:
failed to open stream: No such file or directory in
/srv/disk13/1587290/www/bildungsroman.me.pn/index.php on line 22
Warning: include_once() [function.include]: Failed opening
'simple_html_dom.php' for inclusion
(include_path='.:/usr/local/php-5.3.22/share/pear') in
/srv/disk13/1587290/www/bildungsroman.me.pn/index.php on line 22
Fatal error: Call to undefined function file_get_html() in
/srv/disk13/1587290/www/bildungsroman.me.pn/index.php on line 25
My new code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- page content -->
<?php
include_once('simple_html_dom.php');
$html = file_get_html('http://www.cryptocoincharts.info/v2/api/listCoins');
$result = $html -> find('name');
foreach($result as $element) {
echo $element."<br/>";
}
?>
</body>
</html>
The above PHP script should be in the simple_html_dom.php directory, or use an absolute path instead of the relative path you've used.

Categories