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>
Related
I want to use AJAX to show a form when a user clicks on record to edit it.
I know and capable of using AJAX.
But now i want to call a method of a class in PHP. And thats where im stuck.
Below some code sample of my controller:
public function start() {
$users = $this->usersmodel->getAllUsers();
$firstRow = new HtmlTableFirstRow();
$table = new HtmlTable($users,$users,$firstRow);
$table->setCss('table1');
echo $table->show();
}
public function editRecord() {
$recordId = $this->getFirstParameter();
$user = $this->usersmodel->getUserById($recordId);
$tableId = $this->fieldModel->getTableIdByName('users');
$inputs = $this->fieldModel->getFields($tableId);
$collection = new Fieldcollection($inputs);
foreach($collection as $inputs) {
for($i = 0; $i < count($inputs); $i++) {
foreach($user as $userInfo) {
$inputs[$i]->setValue($userInfo[$i]);
}
}
}
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
}
As you can see i have 2 functions, start which shows all the records. And when a user clicks on editrecord a form will show.
I want to show the form in a popup, without a page refresh.
What is the best way to handle this?
You can make a page for manage ajax requests like this:
server.php :
if(isset($_GET['request'])){
switch($_GET['request']){
case 'get-form' :
$userId = $_GET['userId'];
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
break;
}
}
in client page you can send ajax request & get their result via jquery :
client.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table>
<tr data-userId="1">
<td>User 1</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="2">
<td>User 2</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="3">
<td>User 3</td>
<td><button class="edit">Edit Record</button></td>
</tr>
</table>
<div class="popup">
</div>
</body>
<script src="jquery.js"></script>
<script src="ajax.js"></script>
</html>
ajax.js :
(function(){
$('.popup').hide();
$('.edit').on('click',function(){
var userId = $(this).parent().parent().data('userId');
$.get('server.php',{request : 'get-form' , userId : userId},function(form){
$('.popup').empty().append(form).fadeIn();
});
});
})();
I hope this helps you
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);
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
} ?>
i have a html table that displays values from the database. I have a javascript that enables me to edit this data but then i cant figure out how to save it back to the database using php. i found some information that i should use xmlhttprequests but i have no idea on how to do this. Any suggestions? Your help is highly appreciated. Code below;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript"><!--
function edit_input(obj) {
var is_checked = obj.checked;
while (obj.tagName!='TR')
obj = obj.parentNode;
var td = obj.getElementsByTagName('TD');
var len = td.length;
if (!is_checked) {
for (var i=0; i<len; i++)
if (td[i].className=='editable')
td[i].innerHTML = td[i].firstChild.value;
} else {
var input;
for (var i=0; i<len; i++)
if (td[i].className=='editable') {
input = document.createElement('INPUT');
input.value = td[i].innerHTML;
td[i].innerHTML = '';
td[i].appendChild(input);
}
}
}
--></script>
</head>
<body>
<table border="1">
<tr>
<th width="56">Branch ID</th>
<th width="75">Branch Name</th>
<th width="75">Branch Personnel</th>
<th width="105">Branch Headquaters</th>
<th width="50">Edit</th>
</tr>
<?php
$result = mysql_query($query );
while ($row= mysql_fetch_array($result)) { ?>
<tr>
<td class="editable"><?php echo $row['branchid'];?></td>
<td class="editable"><?php echo $row['branchname'];?></td>
<td class="editable"><?php echo $row['branchpersonnel'];?></td>
<td class="editable"><?php echo $row['branchhq'];?></td>
<td><input type="checkbox" onclick="edit_inpu(this);">Edit</td>
</tr>
<?php } ?>
<tr><td><input type="submit" name="editbranch" class="button2" value="Update"/></td></tr>
</table>
</body>
</html>
If using jQuery is not a problem, maybe using something like JEditable is a solution. When you click on a cell in a table, it turns into a textfield, and when pressing enter or leaving focus, it makes a webrequest to the server, where you can make the changes.
See for example this jsfiddle script. It's really easy to use. The only other thing you would need to do is to give the table cells an id, which gets sent to the page you are saving it too.
Have your script fire off an Ajax request through XMLHttpRequest to a PHP script that saves the values back to the database.
The URL could be something like this: updatetable.php?row=0&col=0&data=1234
You could use jquery, is very popular.
you have to download the lib and include-it on the header
http://code.jquery.com/jquery-1.7.min.js
and here it's how you use a ajax request with jquery:
http://api.jquery.com/jQuery.ajax/
The url param is your location to send the values to save them like the post.
Follow this if you can...
Basically i have an order form (which begins with one row).
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
<a id="add">+</a>
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td width="33%">Product Code (e.g 66203)</td>
<td width="33%">Mtrs Required (e.g 10)</td>
<td width="33%">Preview Image</td>
</tr>
<tr class="item">
<td class="prodcode"><input type="text" name="prodcode[]" id="prodcode" /></td>
<td class="meterage"><input type="text" name="meterage[]" id="meterage" /></td>
<td class="imgsample"></td>
</tr>
</tbody>
</table>
<button>Submit</button>
</form>
Notice the link with an ID of "add". When checked this adds a new row to the table with the same ID. Using the code below.
var counter = 0;
//Order Form
$("#add").click(function() {
counter++;
var cln = $('#ordertable tbody>tr:last').clone(true);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
cln.insertAfter('#ordertable tbody>tr:last');
$('#ordertable tbody>tr:last input').val('');
$('td.imgsample:last a').remove();
return false;
});
//Check for image preview
$("#prodcode").blur(function() {
var $this = $(this);
$this
.closest('tr') // find the parent tr
.find('td.imgsample') // find the imgsample in the row
.html( $(this).attr('id')) // update the contents
//.animate({'opacity':1},200);
var imgsample = $this.closest('tr').find('td.imgsample')
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
});
My PHP in searchimage...
When i currently enter a product code if it is invalid it only puts the productID in td.imsample and i want it to say INVALID CODE
//Find image based on Product Code
function findimage($imageToFind) {
require '../../../../config.php';
$dbh = new PDO(DB_DSN, DB_USER, DB_PASS);
$sql = "SELECT * FROM isproducts WHERE prodCode = ".strtoupper($imageToFind)."";
$stmt = $dbh->query($sql);
$obj = $stmt->fetch(PDO::FETCH_OBJ);
$count = $stmt->rowCount();
if($count > 0) {
$sql2 = "SELECT * FROM imageindex WHERE filename LIKE '".strtoupper($imageToFind)."-%'";
$stmt2 = $dbh->query($sql2);
$obj2 = $stmt2->fetch(PDO::FETCH_OBJ);
echo ($stmt2->rowCount() == 1 ? '<span>'.$obj2->path.'/'.$obj2->filename.'</span> -' : 'No Image Available');
} else {
echo 'Invalid Code';
}
}
//Call Function
findimage($_POST['imgreference']);
try this, can have code errors since I could not test at all:
jQuery Template
HTML:
<script id="template-item" type="text/x-jquery-tmpl">
<tr class="item" id="${id}">
<td class="prodcode"><input type="text" name="prodcode[]" class="prodcode-input" data="${id}" val="" /></td>
<td class="meterage"><input type="text" name="meterage[]" class="meterage-input" val="" /></td>
</tr>
</script>
<form id="orderform" name"orderForm" action="/secure/delivery-details.html" method="post">
+
<table id="ordertable" width="533" border="0" cellspacing="0" cellpadding="2">
<thead>
<tr>
<th width="33%">Product Code (e.g 66203)</th>
<th width="33%">Mtrs Required (e.g 10)</th>
<th width="33%">Preview Image</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<td class="imgsample"></td>
</tfoot>
</table>
<button>Submit</button>
</form>
JS:
$(function() {
var counter = 0;
//Check for image preview
var blur_event = function(ev) {
var
self = $(this),
imgsample = $("#ordertable tfoot .imgsample");
$(imgsample).html( $(this).class() ); // update the contents
$.post('/public/themes/lbd/js/searchimage.php', //this page reads the image code and gives you the image location
{ action: 'searchimage', imgreference: $(self).val() },
function(data) {
$(imgsample).html(data);
}
);
return false;
};
//Order Form
$("#add").bind("click", function(ev) {
counter++;
var cln = $('#template-item').tmpl({id:"item-"+counter);
// cln.find("[id^='prodcode']").each(function(i, val) {
// val.id = val.id.match(/^([^0-9]+)[0-9]*$/)[1] + "" + counter;
// });
$(cln).find(".prodcode-input").bind("blur", blur_event);
$(cln).appendTo('#ordertable tbody');
return false;
});
});
Your problem is most likely due to the duplicated ID. That makes your HTML document invalid. See my explanation here.