adding arrow navigation to Jquery AJAX + PHP search engine - php

I've made a search engine for my database table where the search query gets sent by Jquery AJAX to a file called search.php. Search.php then sends the result back to the Javascript file where the results are processed and added to index.php.
Everything works perfectly except when I try to add arrow key navigation. For example, I want the first item in the search results page to be selected (by appending the class, red to it and using focus()) when I press the down arrow key, the second result to be selected when I press it again, etc..
Nothing gets selected when I press either the up or down arrow key. I'm testing this in Google Chrome.
index.php:
<link rel="stylesheet" type="text/css" href="search.css">
Start searching: <input type="text" id="search" autocomplete="off">
<div id="search_results">
</div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search.js"></script>
javascript file:
$(document).ready(function(){
search_x = $('#search').offset().left;
search_y = $('#search').offset().top;
search_height = $('#search').height();
$('#search_results').css({
'left': search_x,
'top': (search_y + search_height + 5)
});
//arrow key navigation
start = -1;
$(document).on('keydown',document,function(e){
if(e.keyCode == 38){
if (start == -1){
start = ($('#search_results ul li a').size() - 1);
}else{
start--;
if (start < 0){
start = ($('#search_results ul li a').size() - 1);
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
if(e.keyCode == 40){
if (start == -1){
start = 0;
}else{
start++;
if (start > ($('#search_results ul li a').size() - 1)){
start = 0;
}
}
$('#search_results ul li a').removeClass('red').focus();
$('#search_results ul li a').eq(start).addClass('red').focus();
}
});
$('#search').on(
'keyup keydown',
function(){
var search_term = $(this).val();
$.post(
'search.php',
{
search_term : search_term
},function(data){
if (data == "nothing"){
$('#search_results').fadeOut();
} else {
$('#search_results').html(data).fadeIn();
}
});
});
});
part of the search.php file that sends data to index.php:
if (!empty($search_term))
{
echo '<ul>';
while ($results_row = mysql_fetch_assoc($search)){
echo '<li><a href="#">
<p><strong>',$results_row['place'],'</strong><br>',$results_row['description'],'</p>
</a>
</li>';
}
echo '</ul>';
} else {
echo "nothing";
}

I think the problem may be the on() method.
You are attaching the method to the document object, which is fine, but then also passing document as the second argument to the method. The second argument represents a selector that each event is filtered against to see if that was the element that trigerred the event. The document element won't both receive the event and originate the event (unless there are literally no elements on the page!)
try something like:
$(document).on("keydown", "#search_results", function() {
//etc
});
So the document will still receive the event, but the handler will only be triggered if the event originated from the results container

After finding some free time to code again, I changed $(document).on('keydown',document,function(e){
//stuff
}); to $(document).on('keydown','#search',function(e){
//stuff
});
The key press event listener was applied to the text field, #search. The code seemed to work after making the change.

Related

multi image select and print selected images using jquery

i have image set div tag like below:
function printImg() {
pwin = window.open(document.getElementById("mainImg").src,"_blank");
window.print();
}
$(function () {
$("#gallery > img").click(function () {
if ($(this).data('selected')) {
$(this).removeClass('selected');
$(this).data('selected', false);
} else {
$(this).addClass('selected');
$(this).data('selected', true);
}
});
var selectedImageArray = [];
$('#gallery > img').each(function () {
if ($(this).data('selected')) {
selectedImageArray.print(this);
}
});
window.onafterprint = function(){
window.location.reload(true);
}
});
img.selected {
border: 3px solid green;
}
img:hover {
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gallery" id="gallery">
<img name=imgqr[] id="mainImg" src="data:image/png;base64, {!! base64_encode(QrCode::format('png')->size(180)->generate($user->emp_code[$i])) !!} " width="100"; height="80"; >{{$user->emp_first_name}} {{$user->emp_last_name}} {{!!($user->dpt_name)!!}}</td></tr>
</div>
<input class="printMe" type="button" onclick="printImg()" value="printMe" />
i need to select image when user click on it, i added the script for this and it working, but i click print button it doesnt print qrcode image ,in meantime is printing whole page.
I also need check if image is selected and pass through array value to print seleted images +data name.
Window.print() will always print the entire current window. You could bypass this by adding the selected images to a pop up and then print that pop up.
popup = window.open();
popup.document.write("imagehtml");
popup.focus(); //required for IE
popup.print();
You can do this one window for one photo but ofcourse you can also add multiple photo's to one screen and then print it.
Your second question asks for an array with the selected images. Because you use jQuery you can just get them by
allSelectedImages = $('.selected');
You can loop that array en call the function .data() on it to get all data attributes!
Hope this helps!
You're calling print on the main window, call print from the window you opened
function printImg() {
pwin = window.open(document.getElementById("mainImg").src,"_blank");
pwin.print();
}
I do not think if there is any problem with your codes,
try this and let me know
Firefox :
Google Chrome:

JQUERY-PHP-MYSQL - Data from Mysql into a existing DIV list did not respond click event

Im a beginner in PHP, MYSQL, JQUERY.
I intended to load a photo gallery (ul) into a div.
The following snippet works well and the style applied to that element and its children works too.
The WHERE clause is enough to load 12 pictures with only one parameter (TabFotosVisivel=1).
Please check the following snippets out:
INDEX.PHP
<div id="idDivTC">
<ul>
$result = mysql_query("SELECT * FROM TabFotos WHERE TabFotosVisivel=1 ORDER BY TabFotosID DESC LIMIT 0,12");
while($row = mysql_fetch_array($result)){
$caminhoArquivo=$row["TabFotosCamArqMini"];
$descricao=$row["TabFotosDescricao"];
$titulo=$row["TabFotosTitulo"];
echo("<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>");
}//fim do while
</ul>
</div><!-- /idDivTC -->
//-----------style of index.php------------------------
#idDivTC ul li {
display:inline;
}
#idDivTC ul li img{
margin:1px;
float:left;
}
Now I would like to load into the same structure another gallery and I use Jquery to call a page with pure PHP.
The additional parameter to WHERE clause id 'idLido'.
The code is
//------------- jquery of index.php----------------------
$(".claSubMenu").click(function (){
var idLido=$(this).attr("alt");
$.post("miniatura.php", { idLido:idLido})
.done(function(data) {
var arrayRetorno=new Array();
arrayRetorno=data.split("#");
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
});
});
MINIATURA.PHP
<?php
require_once("bd.php");
$idLido=$_POST['idLido'];
$sentenca = "SELECT * FROM TabFotos WHERE TabFotosFKGalerias = ".$idLido." AND TabFotosVisivel=1";
$result = mysql_query($sentenca);
while ($row = mysql_fetch_array($result)){
$titulo=$row['TabFotosTitulo'];
$descricao=$row['TabFotosDescricao'];
$caminhoArquivo=$row['TabFotosCamArqMini'];
$retorno=$retorno."<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>#";
}
echo $retorno;
mysql_close($con);
?>
After retrieve data, Jquery/javascript convert it into an array.
This is my point: I would like, as I said, to read each value of this array and append it to the that element/list, when I invoke
$(".claSubMenu").click(function (){
through
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
It works, but the style doesnt applied anymore.
It seems to me that the former block is not the same the latter, although they have the same ID.
Besides, this click event
$("#idDivTC ul li > img").click(function (e){ ...
calls a JqueryUI dialog window, but It works only on the former structure as well.
How may I achieve my intent?
Thank you
In addition, this is the code to modal dialog window (Ui JQuery):
//--------------------modal of index.php ----------------
$("#idDivTC ul li > img").click(function (e){
e.preventDefault();
var titulo = $(this).attr("title");
var alternativa = $(this).attr("alt");
var imagemObj = new Image();
var caminhoArquivo=$(this).attr("src");
imagemObj.src= caminhoArquivo;
imagemObj.onload = function()
{
var largura=imagemObj.width;
var altura=imagemObj.height;
$(this).clone().dialog({
title: function (){
return titulo+" - "+caminhoArquivo;
},
modal: true,
resizable: false,
draggable: true,
width: function(){
return largura;
}
//fim da funcao da largura
});//fim da da this clone
};// fim da imagem load
});
//-----------------------------
For one, use event delegation to attach your click handlers: $("#idDivTC ul li > img").click(...) becomes $("#idDivTC ul").on("click", "img", ...).
The event isn't fired for the newly created elements because they don't have any click events bound to them.

How to make a secondary document ready function?

Ok this is my issue if anyone can help, please.
I have a href that div id to switch content - I would like to add another document ready function javascript without conflicting with make tab I have already.
Example of make tab already:
<script type="text/javascript">
{literal}
$(document).ready(function(){
function makeTabs(selector) {
var tabContainers = $(selector + ' > div');
tabContainers.removeClass("selected").filter(':first').addClass("selected");
galleryRendered = false;
$(selector + ' > ul a').click(function () {
tabContainers.removeClass("selected");
tabContainers.filter(this.hash).addClass("selected");
$(selector + ' > ul a').removeClass('selected');
$(this).addClass('selected');
if (this.hash == '#Pictures' && !galleryRendered)
{
var galleries = $('.pictures > .ad-gallery').adGallery({
effect : 'slide-hori',
enable_keyboard_move : true,
cycle : true,
animation_speed : 400,
slideshow: {
enable: false
},
callbacks: {
init: function() {
this.preloadImage(0);
this.preloadImage(1);
this.preloadImage(2);
}
}
});
galleryRendered = true;
}
if (this.hash == '#OnTheMap') document.getElementById("Map").map.onContainerChanged();
return false;
}).filter(':first').click();
}
makeTabs('.tabs');
});
{/literal}
</script>
Want to create a second one so I can create tabs inside of an existing div id area/content to switch from photo to video to youtube.
<div class=".tabs"><ul><li>[[Photo]]</li><li>[[Youtube]]</li><li>[[Video]]</li></ul><div id="photo">Test</div><div id="tube">Test</div><div id="vid">Test</div></div>
This will be inside a div id that already exist that uses the first tab creator shown above.
In jQuery you just have to do this:
$(function(){
// code here
});
$(function(){
// more code here
});
Every function declared like this will be executed on domready.

how to remember scroll position of page

I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);

Imitate Google suggest with AJAX and PHP

I want to imitate Google suggest with the following code, which means:
step 1: When user types in search box, the query string will be processed by a server php file and query suggestion string is returned(using Ajax object).
step 2:When user clicks on a query suggestion, it will fill into the search box (autocomplete).
Step 1 is achieved while step 2 is not. I think the problem lies in the .click() method (I use .live() later, but it's still not working). My intention is to use .live() or .click() binding a onclick event to the dynamically created <li> element. Any idea?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script src="jquery-1.4.2.js">
</script>
<style>
#search,#suggest,ul,li{margin: 0; padding:0; width: 200px;}
ul{ list-style-type: none;}
.border{border: solid red 1px; }
</style>
<p>My first language is:</p>
<input type="text" width="200px" id="search" onkeyup="main(this.value)" value="" />
<ul id="suggest"></ul>
<script type="text/javascript">
$(function main(str)
{ //binding any forthcoming li element click event to a function
$('li').live('click', function(){ $("#search").val(array[i]);});
//setup Ajax object
var request=new XMLHttpRequest();
request.open("GET","language.php?q="+str,true)
//core function
request.onreadystatechange=function()
{
if ( request.readyState==4 && request.status==200)
{ if (str=="") {$('li').remove(); $('ul').removeClass('border');return;}
$('li').remove();
reply=request.responseText.split(",");
for (i=0;i<reply.length;i++)
{
//create HTML element of <li>
$('#suggest').append($('<li>',{id: 'li'+i, html: reply[i]}));
//style ul
$('ul').addClass('border');
}
}
}
request.send();
})
</script>
PHP:
<?php
$q=$_GET[q];
$a[]='english';
$a[]='chinese';
$a[]='japanese';
$a[]='eeeeee';
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
You're looking for jQuery Autocomplete.
You're correct about which line is the problem. You're missing the # to search by ID.
$('li'+i).click(function(){ $("#search").html(array[i]);});
should be
$('#li'+i).click(function(){ $("#search").html(array[i]);});
There are much cleaner ways to do this, however, that don't require a re-query of the document to attach this handler. I concur fully with the suggestion to use a plugin.
Also, you might want to wait for the user to be idle. This prevents too many round-trips. This would mean writing something like:
$("input").keyUp(function(e) {
clearTimeout(updater);
updater = setTimeout(whenReady, 200);
}
function whenReady() {
// update the search box here...
}
I went through your code and there are few issues in it.
1) If you want to bind click event on dynamically created elements then you should use .live('click', function(){}) event binder. This jQuery function will bind click event on the selector which will be created later on in the code dynamically so li elements that are coming from the server will automatically be binded to the click event if you write live() event on document ready function. Read docs.
Here is the sample code
<script>
$(function() {
$("#suggest li").live('click', function() {
$("#search").val($(this).text()); // li inner html contains text that needs to put into search box
alert($(this).text()); // or alert(array[i]); in your code
//c what is the out put of above code. better if you change name of an array
});
});
</script>
Also text input elements values are fetch using .val() function instead of .html function in your code $("#search").html(array[i]);
regards
Ayaz Alavi
If you want your application to work correctly, you should also consider to cache the response, in case of backspace for instance.

Categories