I am actually creating a forum. So, there would be a "order by" dropdown box i.e a select tag in html. Where the user selects any order like by time or like, etc. An ajax function is called which dynamically brings content into the page from mysql database.
Select menu
<select name="orderby" onchange="showposts(this.value)">
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
showposts function
function showposts(str){
orderby=str;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
Showposts.php page
$sql = "SELECT * FROM posts order by date desc ";
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine'].";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
Problem
So, the problem here is, I want to use a continuous scroll option like the one which is used in facebook. All the javascripts and jquery libraries I saw use logic that when the user scrolls down to the page, the javascript then places some content after that. But, here I running a while loop which brings the data from database at a time. So, I couldn't implement the javascript code. So, is there any thing that I could do to achieve continuous scroll, like is there any possibility to break the while loop or retrieving entire data and display part by part or anything like that?
javascript for scrolling
function yhandler(){
var wrap=document.getElementById('postsdiv');
var contentheight=wrap.offsetHeight;
var yoffset=window.pageYOffset;
var y=yoffset+window.innerHeight;
if(y>=contentheight){
showposts();
}
}
window.onscroll=yhandler();
Use the PDO class built into php and the query from the database will return all the rows as an array of stdclass objects. Then use PDOStatement::fetchObject() to loop through the array
As you are retrieving the data from server using JavaScript, why don't you put the view with the help of JavaScript instead of PHP.
Try using Asynchronous Javascript Call (AJAX) instead of XMLHttpRequest. This will help you to load data asynchronously which means that even if the the result coming form server take time you can still execute your other javascript codes.
With AJAX implemented, let say you want to fetch 10 Posts at one time, then after fetching first 10 posts, you can print the data for those 10 using JavaScript and simultaneously make a call for another 10.
Prepare a successCallBack function, where you will parse the data received and put that as required for your HTML. You will need to append the posts, so that when the next AJAX returns the result, that gets appended after the last post.
http://www.jquery4u.com/demos/ajax/
You should look into MySQL LIMIT. The limit function takes 2 input variables, start and length. With these 2 variables you can create a paging system; that would go something among the lines of:
showposts function
//Add a global variable to save the current page:
var currentPage = 0;
var currentType = 0;
function showposts(str){
//ALL PREVIOUS CODE, UNCHANGED
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML+=xmlhttp.responseText;
}
}
if(str != undefined){
currentType = str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}
xmlhttp.open("GET","showposts.php?q="+currentType+"&p="+currentPage,true);
xmlhttp.send();
}
Showposts.php page
<?php
$currentPage = intval($_GET['p']);
$numPerPage = 30; //change this to the number of items you want each page
$sql = "SELECT * FROM posts order by date desc LIMIT ".($currentPage * $numPerPage).", ".$numPerPage;
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
?>
Now you need to detect when a user has scrolled to the bottom of the page, then call the following function:
function nextPage(){
currentPage++;
showposts();
}
Related
I have 2 separate dropdown lists. I need to get each dropdown to filter each other. Every example I have seen so far is an example for dropdowns that have the options hard-coded in. Mine uses a query to populate the options.
So how could I correctly have each dropdown menu filter each other?
Here is my HTML for the dropdowns on index.php:
<select id="collector" onchange="showUser(this.value)">
<option value="" selected disabled>Collector Name</option>
<?php foreach($collect->fetchAll() as $name) { ?>
<option class="<?php echo $name['Collector Name'];?>" value="<?php echo $name['Collector Name'];?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date" onchange="showUser(this.value)">
<option value="" selected disabled>Bill Date</option>
<?php foreach($bill_date->fetchAll() as $date) { ?>
<option class="<?php echo $date['Date'];?>" value="<?php echo $date['Collector Name'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
Code that runs each time the dropdown is changed in script tags on index.php:
function showUser(str) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var newTableObject = document.getElementById('billing_table');
sorttable.makeSortable(newTableObject);
}
}
// ---- Gets value of collector dropdown selection -----
var e = document.getElementById("collector").value;
$.ajax({
type: 'GET',
url: 'index.php',
data: e,
success: function(response) {
console.log(e);
}
});
// ---- Gets value of the current selection in any of the dropdowns ----
xmlhttp.open("GET","dropdown-display.php?q="+str,true);
xmlhttp.send();
document.getElementById('billing_table').style.display = 'none';
}
$(document).ready(function(){
var $select1 = $( '#collector' ),
$select2 = $( '#date' ),
$options = $select2.find( 'option' );
$select1.on( 'change', function() {
$select2.html( $options.filter( '[value="' + this.value + '"]' ) );
}).trigger( 'change' );
});
Query on my index.php page:
$collector = "SELECT [Collector Name]
FROM [vSpecial_Billing]
Group By [Collector Name]";
$billdate = "SELECT [Collector Name], [Date]
FROM [vSpecial_Billing]
Group By [Collector Name], [Date]";
I don't want to send the value to my dropdown-display.php page since my queries that populate the dropdowns are on my index.php page. However, if I put the value variable in the query, then it runs that query on load before a collector selection can be made and my bill date dropdown will then not be populated.
EDIT:
I changed the value in the options for the date dropdown to Collector Name instead of Date
I also added the $(document).ready(function() at the end of the middle block of code
I updated the queries that I am using
It filters correctly now, however, on page load, the bill date is unable to selected. It is not populated with any rows. How can I change this?
Also, when I filter it, it defaults to the last date on the list. How can I get it to default to a hardcoded value such as "Date" and then the user can select from the filtered values?
I wrote up a test case, using some example data, and made sure this works. Its a rough example, but I believe its doing what you need. With a lot less cruft in the works. I'm sorry, but I used full jquery, because I cannot be bothered to do long-hand javascript anymore haha (plus I couldn't really follow what you had going on in there).
There will need to be two files: index.php and index-ajax.php (for clarity)
index.php brief:
// note: these do not need to be in prepared statements (theres no variables inside)
$collect = $db->query("SELECT DISTINCT [Collector Name] FROM [vSpecial_Billing]");
$names = $collect->fetchAll();
$billdate = $db->query("SELECT DISTINCT [Date] FROM [vSpecial_Billing]");
$dates = $billdate->fetchAll();
?>
<form id="testForm" action="">
<select id="collector">
<option value="" selected="selected" disabled="disabled">Collector Name</option>
<?php foreach($names as $name) { ?>
<option class="choice" value="<?php echo htmlspecialchars($name['Collector Name']);?>"><?php echo $name['Collector Name'];?></option>
<?php } ?>
</select>
<select id="date">
<option value="" selected="selected" disabled="disabled">Bill Date</option>
<?php foreach($dates as $date) { ?>
<option class="choice" value="<?php echo $date['Date'];?>"><?php echo $date['Date'];?></option>
<?php } ?>
</select>
<input type="button" id="clearchoices" name="clearchoices" value="Clear Choices" />
</form>
Some things to note in the above:
You only need to select by DISTINCT. No need to do GROUP BY to get all unique names, or all unique dates.
I put the results of fetchAll into variables, out of habit, but you can move them into the foreach if you wish.
I removed the class defines you had, because a class with spaces in it (in the case of a Collector Name) can be buggy.
The Clear Choices button is just an example of how to reset those selects after they get filtered and filtered beyond what you can select.
This is the javascript portion (it goes in index.php before or after your form, or in the head):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="Javascript" type="text/javascript">
$(document).ready(function(){
$("#collector").change(function(e){
$.post('index-ajax.php',{filter:'Name',by:$(this).val()},function(data){
$("#date .choice").hide();
$.each(data, function(key,row) {
// $("#date option[value='"+ row.item +"']").show();
$("#date option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#date").change(function(e){
$.post('index-ajax.php',{filter:'Date',by:$(this).val()},function(data){
$("#collector .choice").hide();
$.each(data, function(key,row) {
// $("#collector option[value='"+ row.item +"']").show();
$("#collector option").filter(function(i){
return $(this).attr("value").indexOf( row.item ) != -1;
}).show();
});
},"JSON");
});
$("#clearchoices").click(function(e){ e.preventDefault();
$("#collector .choice").show(); $("#collector").val('');
$("#date .choice").show(); $("#date").val('');
});
});
</script>
That block needs a lot of explaining, because I took all your long-hand javascript and packed it into jquery.
Each select has its own handler event for when it changes.
Each select does its own post ajax, with a different variable define to filter on.
After the ajax returns, it hides all options in the OTHER select. Then enables all options which are returned by the json data of the ajax call. This could be handled differently, but I wanted to present one way of doing it.
A key thing is setting "JSON" for the return handler of the .post() methods. You'll see why in index-ajax.php.
And now the index-ajax.php:
if (isset($_POST['filter']) and isset($_POST['by'])) {// sanity check
$results = array();
if (!empty($_POST['by'])) {
// these _DO_ need to be in prepared statements!!!
if ($_POST['filter'] == 'Name') { $sql = "SELECT DISTINCT [Date] as item FROM [vSpecial_Billing] WHERE [Collector Name] = ?"; }
if ($_POST['filter'] == 'Date') { $sql = "SELECT DISTINCT [Collector Name] as item FROM [vSpecial_Billing] WHERE [Date] = ?"; }
$stmt = $db->prepare($sql);
$stmt->execute(array($_POST['by']));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $results[] = $row; }
}
echo json_encode( $results );
exit;
}
This bit of code is actually pretty straightforward. All it does is determine which filter operation to do, prepares the sql, and then grabs distinct matching rows for output. The key thing though is it outputs as json, so the javascript that called this can handle the data easier!
Now... I had built all this in a test script, and my server hates "fetchAll", so your milage may vary on some of the DB code. I also left out all other form code and db setup handlers and all that. Figuring you have a handle on that.
I hope this helps you out, in some way or other.
EDIT 11/7
I made a slight change because I didn't realize the Collector Names in your db would have characters that would break all of this, oops. Two changes for odd character handling:
The select for collector has its option values wrapped in htmlspecialchars().
The jquery portion for where each select .change event filters, is now filtering by looking for a matching index, using the row.item as a direct variable. Before, it was using it in a value=' row.item ' match, which if the row.item had single quotes (or other bad chars), it would break the whole js event and fail!
Generally when I setup things like this, I use ID's and unique element id tags. That way I am only ever referencing by numbers, and wont run into odd character mash. An example of switching everything to ID's would be involved, and I think you have the gist of whats going on now.
Sorry to add another JavaScript object to the mix. I'm just having a little trouble wrapping my head around this as it is a little more complex than i have ever dealt with.
Like the title states, i'm trying to create a JavaScript Object or perhaps a multidimensional array of a MySQL Database. For testing purposes i'm only using three tables from my database even though eventually it will store tens of tables. These tables are called "Interfaces", "IPAM", and "DNSF".
The reason i would like to complete this task is that, i am trying to create a heavy ajax page which dynamically knows when tables are added, updated, deleted etc, and automatically reflects this without having to add more code. I am doing this by writing javascript with php in addition to various other ajax callbacks spitting out html and variables.
Let me start out with my hardcoded HTML. All other html is created dynamically. This too will soon be created dynamically to add buttons to my website without adding code.
<body>
<div class = "form">
<button type="button" class = "formbutton" value = "Interfaces" onclick="inputChoice('Interfaces')">Interfaces</button>
<button type="button" class = "formbutton" value = "IPAM" onclick="inputChoice('IPAM')">IPAM</button>
<button type="button" class = "formbutton" value = "DNSR" onclick="inputChoice('DNSR')">DNSR</button>
</div>
<div class = "tableDiv" id="myTableDiv" style="height:1000px;width:1000px;border:1px solid #ccc; overflow: scroll;"><table id = "myTable"></table></div>
</body>
Before any buttons or events are executed, the first thign my page does is issue ajax requests within a $( document ).ready(function() { function. My issue is that i have to code a seperate ajax request for every single table. I'll show an example here where i fetch interface table data:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
InterfacesCols = data.split(" ");
InterfacesCols.pop();
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
for(j = 0; j < InterfacesCols.length; j++){
if(InterfacesCols[j] != null){
myString = myString + '<td id = "visibleDef">' + items[i][InterfacesCols[j]] +'</td>';
}
}
myString = myString + '</tr>';
Interfaces.push(myString);
}
});
}
});
This ajax request ultimately creates an array of html strings that are used to create the table. Interfaces[] contains each html row. InterfacesCols contains the names of each column. I have to write this block of code for every single table.
What i want to do is put my "Interfaces[]" like arrays and "InterfacesCols[]" like arrays within a master array so that i can create a template and not have tons of the same code.
Lets call this master array tables. This would allow me to put my ajax in a for loop and loop through every table array rather than hardcode it.
tables[0] would be interfaces[], tables[1] would be ipam etc.
In addition to my ajax request blocks where i initially gather my data from the database. I also have my function "inputChoice(string)", where i actually generate a table from this data. I do so by changing inner html of my table. I dont wan't to have to redirect my page. This works fine, but once again i have to create a new block of code for every single table. These blocks of code are massive right now because they include garbage collection for the DOM and also the code for handling massive data sets(>10,000) without browser slow down. I will refrain from posting that block unless necessary. The ajax calls require the same thing.
Here is the php where i originally create the empty array variables by generating javascript:
<?php
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
echo '<script>';
try{
$stmt->execute();
echo 'var tables = [];';
while($row = $stmt->fetch()){
echo 'var '.$row['TABLE_NAME'].' =[];';
echo 'tables += '.$row['TABLE_NAME'].';';
echo 'var '.$row['TABLE_NAME'].'Cols =[];';
}
echo 'console.log(tables[1]);';
}catch(PDOException $e){
echo $e;
}
echo '</script>';
?>
The above php is only called by using an statement on my index. No Ajax.
The link my ajax calls is this:
<?
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
//$stmt2->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
foreach($colnames as $value){
print $value ." ";
}
?>
The above ajax servers only the purpose of fetching column names and returning the names in a space delimeted string to be parsed and turned into an array via javascript, which you can see in my ajax call.
My getJson ajax code is here:
<?php
include "connect.php";
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
$sql = "SELECT * FROM ".$_GET['table']." LIMIT 17000";
$stmt2 = $DBH->prepare($sql);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
try{
$stmt2->execute();
while($row = $stmt2->fetch()){
foreach($colnames as $value){
if($row[$value] == null){
$row[$value] = "";
}
}
$row = array('id' => $i) + $row;
$items['post'][]=($row);
$i++;
}
}
catch(PDOExcetipn $e){
echo $e;
}
print json_encode($items);
?>
The above php seems slightly redundant to me as i fetch the column names again. However this time i also include the actual data. Line by line.
This is basically all of my code i have written for this project. The only code i did not include was my javascript inputChoice() function. Which as i stated above is very bulky and really doesnt do anything the ajax doesnt do when it comes to utilizing the arrays. This is a massive post, so i apologize for the wall of text. I am not sure exactly what the next step is for me to code this better in the way i described. Any input would be very much appreciated!
If I'm correct you want to automate the table generating.
Your index php block retrieves all tables from the DB.
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
So we need to add those to a master table pseudo code:
tables = [];
for (table in tableSQL)
{
tables[table] = tableSQL[table];
tables[table]['cols'] = [];
}
Now you have a master table array containing all your tables.
Let's loop through these. pseudo code:
for (table in tables)
{
retrieveColsWithData(table);
}
function retrieveColsWithData(tableKey)
{
//table = key = table name in DB
$.ajax({url:"/ryan/nonEmber/ajax.php?table="+table, etc.
//rest of the ajax call you're doing. Pass the key var to the JSON function
});
}
The function above loops through all the tables and retrieves the colls. When the JSON request returns you simply add the colls to table[key]['cols'].
Now you can simply iterate over the tables master with a for in or Object.keys and draw the HTML containing the data.
You can reuse retrieveColsWithData connected to your inputChoice to reload the data.
I have an AJAX script running on my website that is supposed to update a dependent dropdown menu (a SELECT options menu) after a previous dropdown menu onchange event happens.
When I click on the first dropdown, the second dropdown does seem to be populated with the correct values from a MySQL database query. However, under my values I also seem to be pulling in the contents on the entire HTML webpage as a whole.
I'd like to know how to only bring in my values without loading the whole webpage again inside of my SELECT options menu.
My Javascript:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp_aris=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp_aris=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_aris.onreadystatechange=function()
{
if (xmlhttp_aris.readyState==4 && xmlhttp_aris.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp_aris.responseText;
}
}
xmlhttp_aris.open('GET','http://mywebdomain.com?ajax=true&q='+str,true);
xmlhttp_aris.send();
}
</script>
My PHP code:
// begin my ghetto code
if ($_GET['ajax'] == 'true') {
$q = $_REQUEST["q"];
$con = mysqli_connect('localhost','db_user','db_pass','db_name');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql='SELECT DISTINCT
employees.firstName,
employees.lastName
FROM
sales_reps
INNER JOIN employees ON sales_reps.employeeId = employees.employeeId
INNER JOIN sales_campaign ON sales_campaign.salesCampId = sales_reps.saleCampId
WHERE
sales_campaign.marketId = '.$q.' AND
employees.isactive = 1';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['firstName'] . '">'
. htmlentities($row['firstName']) .' '.htmlentities($row['lastName']) .'</option>';
}
mysqli_close($con);
}
// end my ghetto code
My code on the page with the dropdown menus:
<select id="frm-marketid" name="frm-marketid" onchange="showUser(this.value)">
<option value="">Choose a Market</option>
<option value="74">Annapolis</option>
<option value="61">Anne Arundel</option>
<option value="26">Aventura</option>
<option value="63">Baltimore</option>
</select>
<br/>
<select id="txtHint"><b>Person info will be listed here.</b></select>
just kill your script after you output your response for ajax
...
}
mysqli_close($con);
exit;
}
...
i make some sort of a shopping cart that when i press on a table line it suppose to open some details about the item, for this purpose i used a div which is at height 0 and hidden at first which contains the details, the problem is that i think that the browser will load the the info pages regardless of if the line was pressed or not. is there any way to make the browser load the page only when his DIV is visible?
$int = 0;
echo "<table class=\"result_table\" id=\"result_table\">";
foreach($types as $data){
echo "<tr onClick=\"present(".$int.");\" >";
echo "<td align=\"right\">";
echo $data['number'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['item_name'];
echo "</td>";
echo "<td align=\"right\">";
echo $data['amount'];
echo "</td>";
echo "<td align=\"right\">";
echo "17";
echo "</td></tr>";
echo "<tr class=\"info_row\"><td colspan=\"4\"><div id=\"div_num_".$int."\" style=\"height:0px\">
<object type=\"text/html\" data=\"page.php\" style=\"width:100%; height:100%; margin:0%;\">
</div></td></tr>";
$int++;
}
echo "</form></table>";
the css for the row
.info_row{
visibility:hidden;
}
the JS:
function present(item_id){
var div = document.getElementById("div_num_"+item_id);
if(div.style.visibility=="visible"){
div.style.visibility = 'hidden';
div.style.height= '0';
} else {
div.style.visibility = 'visible';
div.style.height= "200px";
}
}
as you can see all the info loads with the page but are invisible.
other good ways of tackling this problem will be appritiated especially if it does not include jquery because i am not really strong in it.
thanks in advance.
Firstly, if there isn't much info to load, preloading the data is probably more sensible anyway. Users want a responsive UI, even if it means a few extra milliseconds of initial download time for data they'll never see.
But, if you insist on loading the data separately, you could use an xmlhttprequest to load a representation of the data (such as in JSON), and use a templating solution to output the result into the info div.
The page that might generate the JSON representation of the data might look something like this:
<?php
$result = array();
// ... Code that defines type ... //
$int = 0;
foreach($types as $data){
$result[] = array(
"int" => $int,
"number" => $data["number"],
"item_name" => $data["item_name"],
"amount" => $data["amount"]
);
$int++;
}
echo json_encode($result);
?>
So, when a user clicks a link, the above page would load in an xmlhttprequest. You could then parse the result with JSON.parse(req.responseText), and apply an HTML template to the result (check out the above link, plus this one, for more info on how to do that).
Again, you're probably fine just loading all the data in one go. Extra HTTP headers actually make pages take longer to completely load.
You can use an ajax call:
with javascript
<script type="text/javascript">
function loadInfoRow()
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var responseText = xmlhttp.responseText;
//Use the response text to add the extra row
}
}
xmlhttp.open("GET","info.txt",true);
xmlhttp.send();
}
</script>
with jquery
$.ajax({
url: "info.txt",
context: document.body,
success: function(text){
//where text will be the text returned by the ajax call
$(".result_table).append(text);
}
});
I am having problem with XMLHttpRequest object in IE9, IE8 and probably IE7 too, although have not tested in IE7. It works without problem in FF4, Opera 11.01 and Chrome 10.
First I would like to explain for what I use this code. I have a HTML select tag, with option Time defined in it. Then when the user clicks on a button, it dynamically updates select with time values from database. Now here is the code for creating XMLHttpRequest object:
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
}
As you can see, if the creation of XMLHttpRequest object fails, it tries to create ActiveXObject.
Now the code for sending request and getting response:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(time).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getTime.php?d=" + str, true);
xmlhttp.send();
I send the parameters to getTime.php, and the response is written back to select tag with id=time. Now in IE9 and IE8 it does not want to populate the select tag with time from DB.
EDIT:
I will add code from getTime.php:
<?php
$username="something";
$password="";
$database="somethingDB";
$date = $_GET["d"];
$timestamp = strtotime($date);
$nextDay= $timestamp + (1 * 24 * 60 * 60);// 7 days; 24 hours; 60 mins; 60secs
$date2 = date('Y/n/j', $nextDay);
$link = mysql_connect('localhost', $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $link);
$query="SELECT TIME(Date) FROM someTable WHERE Date >= '" .$date. "' AND Date < '" .$date2. "'";
$result=mysql_query($query);
if (!$result) {
die('Could not query:' . mysql_error());
}
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option>" .$row[0]."</option>";
}
mysql_free_result($result);
mysql_close($link);
?>
EDIT2:
Ok, I have added wrap, according to this. Now I will also post the code select tag, which is now wrapped:
<div id="wrap">
<select id="Time1" name="Time1" disabled="disabled">
<?php if (empty($_GET['Time1'])) { echo "<option>Ura</option>"; } else { echo '<option>' . $_GET['Time1'] . '<option>'; } ?>
</select>
</div>
The code in getTime.php is now also changed, I will post only the section which is changed:
echo '<select id="Time1" name="Time1">';
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option>" .$row[0]."</option>";
}
echo '</select>';
As you can see, I only added echo '....' before and after while statment. Guess what happens now. In FF, Opera and Chrome it works without a problem, but in IE9, it now gets the values, but it does not put them in the drop down menu, it just prints them as actual text. Also the drop down menu has dissapeard when the values are printed as text. Seems like it does not want to include select tag. I don't get it, why is that only with IE?
I have found the right solution here. I already had the select tag in the div box, the missing code was this part:
document.getElementById('box').style.display = 'block';
Apparently without this, the IE will just print it as actual text, instead of populating the select object.
IE has problem with 'select' tag. You cannot just replace the 'option' tags inside only, you have to replace the opening and closing 'select' tags also.