In-Page Result Live Search - php

I need a search box that would throw a result just like how the CTRL+F works.
Right now, on my index.php page I have the ff format:
<table width="100%">
<thead>
<tr>
<th><strong>Client Name:</strong></th>
<th><strong>Nationality:</strong></th>
<th><strong>Birthday:</strong></th>
<th><strong>Address:</strong></th>
<th><strong>Gender:</strong></th>
<th><strong>Birthplace:</strong></th>
</tr>
</thead>
<?php
$sql=mysql_query(" select * from tenant order by id asc");
$count=0;
while($row=mysql_fetch_array($sql))
{
$client_id = $row['id'];
$clientName = $row['cname'];
$cbday = $row['bday'];
$cadd = $row['address'];
$cgender = $row['gender'];
$cbirth = $row['birthplace'];
if($count%2)
{
?>
<tbody>
<?php } else { ?>
<tr id="<?php echo $id; ?>">
<?php } ?>
<td>
<span class="text"><?php echo $client_id.". ".$clientName; ?></span>
</td>
<td>
<span class="text"><?php echo $cbday; ?></span>
</td>
<td>
<span class="text"><?php echo $cadd; ?></span>
</td>
<td>
<span class="text"><?php echo $cgender; ?></span>
</td>
<td>
<span class="text"><?php echo $cbirth; ?></span>
</td>
</tr>
</tbody>
<?php
$count++;
}//while-end
?>
</table>
I've already tried many JQuery and Ajax tutorials but none of them seems to work fine with a value. So I just got into conclusion that perhaps those tutorials could only work only if you have a pre-defined value for the table rows. Like this one for example:
<th>ClientName</th>
Anyway I can have a CTRL+F like search on my index page for the table rows?

Javascript, especially in combination with jQuery is very easy to learn and understand. No need for plugins or tutorials.
How to search the table?
Here is a jsfiddle I just wrote for you:
http://jsfiddle.net/j9U52/
$('#search-submit').on('click', function(event) {
var v = $('#search-value').val(); // get the search value
var t = $('.searchable td'); // WHERE to search
var c = 'highlight'; // css class to add to the found string
// for each td in the table
$.each(t, function(idx, el) {
// find the keyword
var regex = new RegExp("\\b" + v + "\\b", "gi");
// replace it and add a span with the highlight class
el.innerHTML = el.innerHTML.replace(regex, function(matched) {
return "<span class=\"" + c + "\">" + matched + "</span>";
});
});
});
I did not add to reset the highlighted matches when you enter a new search keyword, I leave this up to you :-) Hint: Add something like t.removeClass(c);

Related

Colspan from table doesn't work correctly

I have an HTML table, where if you click on the “<?php echo $row["title"]; ?>“, for each row, it will display the exercise text corresponding to that title.
This is working fine, it toggles correctly but I don’t know why the doesn’t work. The title only displays in one of the columns, but I would like to display on the 3 of them. Below I post a picture with what I get.
Can you help me solve this?
This is my code:
<tr>
<td><?php echo $num_ex; ?></td>
<!---Click Toggle Exercise-->
<td><a onclick="myFunction(<?php echo $row["exercise_id"] ?>)" role="button" class="btn" target="_blank" ><?php echo $row["title"]; ?></a>
</td>
<td><?php echo $row["difficulty"]; ?></td>
</tr>
<!--- Toggle --->
<tr id="toggle<?php echo $row["exercise_id"] ?>" style="display:none">
<td colspan="3"> <!---THIS COLSPAN IS NOT WORKING-->
<?php
$sql = "SELECT * FROM exercises WHERE exercise_id='".$row["exercise_id"]."'";
$result_ej = $conn->query($sql); /*Check connection*/
$row_ej = $result_ej->fetch_assoc();
?>
<p><?php echo $row["exercise_id"] . ". " . $row["text"]?></p>
</td>
</tr><!---Finish Toggle --->
This is my script:
<script>
function myFunction(ejer_id) {
var x = document.getElementById("toggle" + ejer_id);
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Since you are changing the display of a <tr> you need to set it properly when you need to show it or else it does not obey table structure rules.
The issue is:
x.style.display = "block";
It should be:
x.style.display = "table-row";
Or, better yet just unset it if you don't want to keep track of the "correct" value:
x.style.display = "";
disclaimer: I do not know if all browsers will properly support this third option.
See https://stackoverflow.com/a/7971565/2191572 for other options.
You can also use:
x.style.display = "initial";
but it may not work in all browsers such as IE 11 and earlier per https://developer.mozilla.org/en-US/docs/Web/CSS/initial#Browser_compatibility

How to sum grouped values from a table? For example I will sum the name?

How do I sum grouped values from a table? For example I will sum the name?
this values :
2.997,
7.497
return : result!
I already have a function which delivers the whole sum this works fine. But I have don't a clue how to solve this problem ![enter image description here][1]
here is my function for the whole sum!
function calculateSum() {
var sum = 0;
$(".overviewTaxes").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$( ".globalTaxSum" ).html(sum);
}
<tbody>
<?php foreach ($overviews as $overview): ?>
<tr>
<td >
<?php echo $overview["forename"] . " " . $overview["surname"]; ?>
</td>
<td>
<?php echo $overview["article"]; ?>
</td>
<td>
<?php echo $overview["articleprice"]; ?>
</td>
<td class="overviewTaxes">
<?php
$ps = $overview["articleprice"] * 0.3; //flat rate
echo round($ps, 3) ;
?><br/>
</td>
</tr>
<?php endforeach; ?>
</tbody>
Thanks for help.
Best regards
Marc Kevin

On hover show image from data attribute from google image search

I am trying to incorporate a code that will allow me to assign a class to a table that is "hoverme" then once a user hovers over that cell, it then does an ajax query to using the data-attribute with the information stored in there to a google search.
here is a mock up table:
<table>
<thead>
<tr><td>Test</td><td>Name</td></tr>
</thead>
<tbody>
<tr><td data-info="Samsung NP200A5B" class="hoverme">ABC123</td><td>Test Name</td> </tr>
</tbody>
</table>
Once a user hovers over the name abc123 it should show a pic above it of what is in the data-info tag.
I am not sure of how the jquery is going to work nor do i know if this is even going to work because everything is generated from a MySQL database.
here is my php code:
<?php
$qry = "SELECT * FROM `assets` WHERE cust_id='$custID'";
$rs = mysqli_query($mysqli,$qry) or die("Error: ".mysqli_error($mysqli));
if(mysqli_num_rows($rs) > 0)
while($rowa = mysqli_fetch_array($rs)) {
echo '
<tr>
<td>'.$rowa['asset_tag'].'</td>
<td>'.ucwords ($rowa['type']).'</td>
<td>'.ucwords ($rowa['vendor']).'</td>
<td>'.ucwords ($rowa['model']).'</td>
<td>'.ucwords ($rowa['platform']).'</td>
<td>'.ucwords ($rowa['location']).'</td>
<td>'.ucwords ($rowa['status']).'</td>
<td>'.ucwords ($rowa['user']).'</td>
<td><a data-toggle="modal" href="#myModal" id="'.$rowa['id'].'">View</a></td>
<td>Edit</td>
<td>'?> <?php if($rowa['del_flag'] == 0){ echo' Delete'; }else{ echo 'Undo Delete'; }?> <?php echo '</td>
<td><span class="glyphicon glyphicon-qrcode"></span></td>
</tr>'.PHP_EOL;
}else
echo "
<tr>
<td>No assets found</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr> ".PHP_EOL;
?>
One last thing i should mention is i am using Jquery's DataTable.
This can be through the Google Image Search API, but with the daily usage limit (or pay $5 per 100 search).
See: https://developers.google.com/image-search/
Even using this API, you cannot ensure that the every searched image matches as the one you expecting to show in your page.
Sample API:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
function addPaginationLinks() {
// To paginate search results, use the cursor function.
var cursor = imageSearch.cursor;
var curPage = cursor.currentPageIndex; // check what page the app is on
var pagesDiv = document.createElement('div');
for (var i = 0; i < cursor.pages.length; i++) {
var page = cursor.pages[i];
if (curPage == i) {
// If we are on the current page, then don't make a link.
var label = document.createTextNode(' ' + page.label + ' ');
pagesDiv.appendChild(label);
} else {
// Create links to other pages using gotoPage() on the searcher.
var link = document.createElement('a');
link.href="/image-search/v1/javascript:imageSearch.gotoPage("+i+');';
link.innerHTML = page.label;
link.style.marginRight = '2px';
pagesDiv.appendChild(link);
}
}
var contentDiv = document.getElementById('content');
contentDiv.appendChild(pagesDiv);
}
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the
// title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src="/image-search/v1/result.tbUrl;"
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
// Now add links to additional pages of search results.
addPaginationLinks(imageSearch);
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
// Include the required Google branding
google.search.Search.getBranding('branding');
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="branding" style="float: left;"></div><br />
<div id="content">Loading...</div>
</body>
</html>

Change "value" of a <input> while clicking on query result, while more than one record

I have a script that would change the value of a input field:
<script language="javascript">
function klientid() {
var getid = document.getElementById("getidfromsearch");//results
var klid = document.getElementById("idklienta"); //input field
if(getid != "0") {
klid.value = getid.textContent;
}
</script>
a search engine and this is how results are printed:
<?php
while($rowmilion = mysqli_fetch_array($resultmilion)) {
?>
<a href="javascript:klientid()">
<table>
<tr>
<td style="font-weight:bold; width: 160px; text-align:right;">ID:</td>
<td style="width:200px;" id="getidfromsearch"><?php echo $rowmilion['id']; ?></td>
</tr>
</table>
</a>
<?php } ?>
Now, when as the result there is only one record and I click on the link, it does change the value of a input field fine.
When result consists of more than one record, whichever link I would click, it will always get the value from the first record for example:
ID: 100
ID: 200
ID: 300
So when I click on the third position, it will still change the value of a input field to 100 instead of 300.
I quess, this is because all records get the same "ID"... But still, I can't make it work.
You should give an unique ID for each result or it will screw up your getElementById search.
Your JS code :
<script language="javascript">
function klientid(domElmtId) {// ** I added a parameter
var getid = document.getElementById(domElmtId);//results
var klid = document.getElementById("idklienta"); //input field
if(getid !== null) {// ** This is better
klid.value = getid.textContent;
}
</script>
Your Php code
<?php
$count = 0;//** I added a variable to give each result a different ID
while($rowmilion = mysqli_fetch_array($resultmilion)) {
?>
<a href="javascript:klientid('result<?php echo $count; ?>')">
<table>
<tr>
<td style="font-weight:bold; width: 160px; text-align:right;">ID:</td>
<td style="width:200px;" id="result<?php ?>"><?php echo $rowmilion['id']; ?></td>
</tr>
</table>
</a>
<?php
$count += 1;//** to make different IDs
} ?>

how to invoke JS/ajax with no submit button on the page?

i have a website page that contains only data of which one field gives the number of messages in your inbox, and i need to refresh this as new messages can some in at any time, so the user, while on this page can see there are new messages. how can i call my JS/ajax to do the refresh please?
i tried header("Refresh:10"); but client was not happy as it refreshes the whole page, he only wants the no of messages to refresh as they come in...can someone help please? thanks
my code for this page:
<?php use_stylesheets_for_form($search_form) ?>
<?php use_javascripts_for_form($search_form) ?>
<div id='div_longgray_gradient2'>
<div id='div_float_img'>
<br/>
<table width='96%' border='0'>
<tr>
<td colspan='2' align='right'>
<form action="<?php echo url_for('profiles/search' ) ?>" method="post" >
<table>
<tr>
<td>
<span class='spn_med_lightblue_rbc'>Profile Search
</span>
<?php echo $search_form['uc_other']->render(array('default')); ?> </td>
<td><input class='submit_img' type="image" src="/images/rainbow/gobuttonbluesmall.png" value="Submit" alt="Submit"></td>
</tr>
</table>
</form>
</td>
</tr>
<tr>
<td rowspan='2' width='40px' align='left'>
<img src='/images/rainbow/arrow.png'>
</td>
<td align='left'>
<span class='spn_big_black_rbc'>WELCOME <?php echo $usr_profile->getName() ?></span>
</td>
<td align='left'>
<?php
if (0)
{
// $filename = $usr_profile->getMsisdn();
$filename = $usr_profile->getProfilePicPath();
if ($filename && file_exists($filename))
{
$source = imagecreatefromjpeg($filename);
}
else
{
$filename = $usr_profile->getDefaultProfilePicPath();
$source = imagecreatefromjpeg($filename);
echo "<span class='spn_big_black_rbc'>You have not uploaded an image yet</span>";
}
}
if($usr_profile->existsProfilePic()==FALSE)
{
echo "<span class='spn_big_black_rbc'>You have not uploaded an image yet</span>";
echo "</br>";
}
if($usr_profile->checkForMissingInfo()== 1)
{
echo "<span class='spn_big_black_rbc'>You have some missing info</span>";
echo " ";
echo link_to('Edit','profile/edit','class=link_medium');
}
?>
</td>
</tr>
<tr>
<td align='left'>
<span class='spn_med_lightblue_rbc'>TO RAINBOW</span>
<span class='spn_med_black_rbc'>CODE</span>
<span class='spn_med_lightblue_rbc'>...SHINE ON</span>
</td>
<td>
</td>
</tr>
</table>
<br/>
<table class='table_border_light' width='820px'>
<tr>
<td class='td_header_blue' colspan='3' align='left'>
<span class='spn_big_black_rbc'>
MY FEEDS
</span>
</td>
<td class='td_header_blue' colspan='3' align='left'>
<span class='spn_big_black_rbc'>
RAINBOWCODE NEWS
</span>
</td>
</tr>
<tr>
<td valign='top' colspan='3' width='50%' align='left'>
<span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>
<?php echo link_to('Messages','messagebox/list','class=link_medium_blue'); ?>
</br>
<span class='spn_med_black_rbc'>You have
<?php
echo sizeof($block_records);
?> blocked users </span>
</td>
<td valign='top'colspan='3' width='50%' align='left'>
<ul>
<li>
<a href="http://spreadsheets.google.com/a/miranetworks.net/spreadsheet/viewform?formkey=dEVlYTdJTzZiU0JPTnZqYWlZQTJRZ0E6MQ" class='link_medium_blue'> Rate us! Complete the online questionnaire</a></b>
</li>
<?php
foreach($news as $news_item)
{
echo "<li>".$news_item->getNews(). "</li>";
$newsId = $news_item->getId();
if ($newsId == 1)
{
//some echos here to display text
}
}
?>
</ul>
</td>
</tr>
<tr>
<td colspan='3' align='left'>
<span class='spn_big_black_rbc'>
MOOD BAROMETER
<?php echo link_to('how does it work?','util/barometer','class=link_medium_blue'); ?>
</span>
<?php
include_component('profile','moodmetershow');
?>
</td>
<td colspan='3' align='left'>
<?php
include_component('profile','moodmeter');
?>
</td>
</tr>
<tr>
<td colspan='3' align='left'>
</td>
</tr>
</table>
</div>
</div>
i added this for $new_mail_cnt:
echo $new_mail_cnt = '<script type="text/javascript">getMessages();</script>';
then i have:
<script language="JavaScript" type="text/javascript">
var receiveReq = getXmlHttpRequestObject();
var mTimer;
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
document.getElementById('p_status').innerHTML =
'Status: Cound not create XmlHttpRequest Object.' +
'Consider upgrading your browser.';
}
}
function getMessages()
{
receiveReq = getXmlHttpRequestObject();
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
receiveReq.open("POST", 'getMessage.php', true);
receiveReq.onreadystatechange = handleReceiveMessage();
receiveReq.send(null);
document.getElementById('new_messages').innerHTML = receiveReq.responseXML; //not sure here
}
mTimer = setTimeout('getMessage();',2000);
}
function handleReceiveMessage()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
}
}
</script>
AJAX is a technology which allows you to launch web requests to a server after the page is loaded. When using an AJAX request, the page does not have to reload (indeed, the user won't even notice a request is taking place).
You should launch an AJAX request to your server, which will check for any new messages.
To continuously check for new messages, you could create a timer using either the window.setTimeout, or the window.setInterval methods, to launch an AJAX request at designated periods.
Whilst I am not a big fan of promoting using libraries when a question does not mention any use of them, you may find that using one (such as jQuery), will greatly simplify the process of managing AJAX requests, as it comes with a complete module which does the hard work for you.
Regardless of whether you choose to use a library to perform your AJAX request or not, the workflow for the solution will be as follows:
On a timer (every 10 seconds say, launch an AJAX request) to a webpage on your server (e.g checkfornewmessages.php).
On your server, check for any new messages, and include what you want to display to the user in the output (e.g. the number of new messages, the title of the messages, whatever).
In your callback for your AJAX request, set the response of the AJAX call (which will contain the output you created in your PHP code), to the contents of one of the DOM elements on your page (e.g. <span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>).
Try timer in javascript http://www.w3schools.com/js/js_timing.asp
I am assuming in your use_javascripts_for_form($search_form) you have a jQuery reference somewhere if not you can download it and include it in the headers
======NOTE UNTESTED======
Change the following line
<span class='spn_med_black_rbc'>You have <?php echo $new_mail_cnt ?> new </span>
to
<span class='spn_med_black_rbc'>You have <div id='newMessageDiv'><?php echo $new_mail_cnt ?></div> new </span>
Add something like the following into the HEAD tag
$(document).ready(function() {
$("#newMessageDiv").load
("newMessageCheck.php");
var refreshId = setInterval(function() {
$("#newMessageDiv").load('newMessageCheck.php?randval='+ Math.random());
}, 10000);
$.ajaxSetup({ cache: false });
});
This will attempt to refresh the div every 10 seconds with the contents of newMessageCheck.php, this file should just output a single value of just the amount of current new messages.
you put:
setTimeout(samefunction,milliseconds)
in the function that you want to auto-recharge and call the same
this create a infinite loop waiting x milliseconds

Categories