Add arrow navigation to Ajax live search - javascript

I'm building an AJAX live search, it works but I would like to navigate using keyboard arrows (up/down). I don't know how I can do this.
My form.php
<div class="input-group" id="nav-input-group" style="display:table;">
<input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick="">
<div class="result"></div>
</div>
My script
$(document).ready(function(){
$('#nav-input-group input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("_ajax_search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents("#nav-input-group").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
and _ajax_search.php
<?php
require('bdd_pdo_connect.php');
try{
if(isset($_REQUEST['term'])){
$sql = "SELECT * FROM subcategories WHERE subcategory LIKE :term";
$stmt = $bdd->prepare($sql);
$term = '%' . $_REQUEST['term'] . '%';
$stmt->bindParam(':term', $term);
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row['subcategory'] . "</p>";
}
} else{
echo "<p>No matches found";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
unset($bdd);
?>
I'm new with AJAX and any help will be greatly appreciated.

Why don't you use HTML select tag to make a dropdown list? It supports arrow keys navigation by default. If you want all options to appear, use the size attribute of the HTML select tag (see HTML5 size attribute specification).
HTML
<div class="input-group" id="nav-input-group" style="display:table;">
<input name="q" id="thesearchbar" class="form-control input-search " name="search" placeholder="Serach..." autocomplete="off" type="text" onclick="">
<select class="result" size="10"></div> <!-- size="10" is an example here -->
</div>
JS
// (ajax part)
// ...
$(document).on("change", ".result", function(){
$(this).parents("#nav-input-group").find('input[type="text"]').val($(this).val());
$(this).empty();
});

Related

in my code i unable to get image name , or image preview in wordpress setting page please give some solution

This is my code here I can't get image name to store in a database, and I can't see image preview also when it selected.
add_action('admin_footer',array(&$this,'media_selector_print_scripts'));
public function media_selector_settings_page_callback(){
if(isset($_POST['submit_image_selector'])&&
isset($_POST['image_attachment_id'])):
update_option('media_selector_attachment_id',absint($_POST['image_attachment_id']));
endif;
wp_enqueue_media();
if(isset($_POST['submit'])){
$category = $_POST['category'];
$type = $_POST['type'];
$name = $_POST['name'];
$description = $_POST['description'];
$img_path = get_option('media_selector_attachment_id');
$insert_data = new insert_Data();
$insert_data-
>insert_table_data($category,$type,$name,$description,$img_path);
}
?>
WordPress setting page design HTML
<h1>Plugin page</h1>
<form method="post" action="" enctype="multipart/form-data">
<br><br><br>
<input type="text" name="category" placeholder="category"/><br><br>
<input type="text" name="type" placeholder="type"/><br><br>
<input type="text" name="name" placeholder="name"/><br><br>
<textarea name="description" placeholder="description"></textarea>
<br><br>
<div class="img-preview-wrapper">
<img id="img-preview" src="<?php echo
wp_get_attachment_url(get_option('media_selector_attachment_id')); ?>"
height="100px"/>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e('Upload image'); ?>"/>
<input type="hidden" name="image_attachment_id" id="image_attachment_id" value="<?php echo get_option('media_selector_attachment_id'); ?>"/>
<input type="submit" name="submit" value="Save" class="button-primary"/>
</form>
<?php
}
this is jquery script
public function media_selector_print_scripts(){
$my_saved_attachment_post_id = get_option('media_selector_attachment_id',0);
?>
<script type="text/javascript">
jQuery(document).ready(function($){
//uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id;//store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id;?>;
jQuery('#upload_image_button').on('click', function (event) {
event.preventDefault();
//if the media frame already exists, reopen it
if (file_frame){
//set the post id to what we want
file_frame.uploader.uploader.param('post_id', set_to_post_id);
//open frame
file_frame.open();
return;
} else {
wp.media.model.settings.post.id = set_to_post_id;
}
//create the media frame
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple:false
});
file_frame.on('select', function () {
attachment =
file_frame.state().get('selection').first().toJSON();
$('#image-preview').attr('src',attachment.url).css('width','auto');
$('#image-attachment-id').val(attachment.id);
wp.media.model.settings.post.id = wp_media_post_id;
});
file_frame.open();
});
jQuery('a.add-media').on('click', function(){
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>
<?php
}
This is my code here I can't get image name to store in a database, and I can't see image preview also when it selected.This is my code here I can't get image name to store in a database, and I can't see image preview also when it selected.This is my code here I can't get image name to store in a database, and I can't see image preview also when it selected.
In php file you have a check for isset($_POST['submit_image_selector']) but I don't see such a field in html.
Try to replace it with isset($_POST['submit']).

Using livesearch textbox twice in a same page

I have used the below code for Livesearch in my webpage and it works fine in the student form. But in the index page for second text box(Staff form), live search is not working. I hope this is due to the use of JQuery function using attribute ID which is same for both input text box. Is there anyway to make the live search work in second text box without changing the entire code?
Thanks in advance
livesearch.js
$('#college').keyup(function(e)
{
if ( key != 40 && key != 38 && key != 13 ) livesearch();
}
function livesearch() {
var min_length = 1; // min caracters to display the autocomplete
var keyword = $.trim($('#college').val());
if (keyword.length >= min_length) {
$.ajax({
url: 'livesearch.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#college_list').show();
$('#college_list').html(data);
}
});
} else {
$('#college_list').hide();
}
}
index.php
<div id="student">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
<!-- Another Division similar to previous one-->
<div id="staff">
<form action="/" method="post">
<div class="field-wrap">
<input type="text" id="college" placeholder="College Name" required
autocomplete="off"/>
<ul id="college_list"></ul>
</div>
<button type="submit" class="button button-block"/>Get
Started</button>
</form>
livesearch.php
$parts = explode(' ', $keyword);
$p = count($parts);
$sql = "SELECT * FROM colleges WHERE college_id is not null";
for($i = 0; $i < $p; $i++) {
$sql .= " AND college_name LIKE '%$parts[$i]%'";
}
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// Highlight the written text
$college_name = highlight($keyword,$rs['college_name']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'",
$rs['college_name']).'\')">'.$college_name.'</li>';
}
You're targeting elements with an id - in the first line:
$('#college').keyup(function(e) { ... }
If you switch that to a class, such as .live-search and add this class to your HTML element, the script should naturally work on multiple elements.
ID's in HTML should be unique, whereas classes can be applied to multiple elements.
Update: You might also need to switch this line:
var keyword = $.trim($('#college').val());
To reference this instead:
var keyword = $.trim($(this).val());
This will ensure that when you detect a keyup on that element, that the script acts upon that one particular element.

Unable to Pass Values from One PHP Page to Another

There is similar code in the application that works in this same fashion, but my addition is not working. I can get the search page to pop-up in a new window, but when I select the group to pass to the form page and display the pop-up window will not close or populate the form field on the add form page. Any help would be appreciated.
ADD Form PHP Page
Want to hide a readonly form field for a group name and display a button to search group listing from another page.
Form Field Page HTML Code
<div class="form-group">
<label class="col-sm-3 control-label" for="groupId">Group *</label>
<div class="col-sm-6" id="div_gr_name" style="<?php if ($gr_id < 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">>
<input type='text' name='gr_name' class='span2 form-control' placeholder="Search Group Name" value="<?php if ($gr_id != -1) {echo $gr_name;} else {echo '';} ?>" id='gr_name' readonly='true' required/>
</div>
<div class="col-sm-2" style = "<?php if ($gr_id > 1) {?> display:none <?php } else { ?> display:inline <?php } ?>">
<button type="button" class="btn btn-primary" onclick='OpenPopup()'>Search</button>
</div>
<div>
<span id='paientNameMissing'></span>
</div>
</div>
Javascript OpenPopup from footer page
function OpenPopup() {
try {
window.open("searchgroup.php", "_blank", "width=850,height=500,scrollbars=yes,resizable=yes");
}
catch (ex) {
alert(ex);
}
finally {
event.cancelBubble = true;
event.returnValue = false;
return false;
}
}
Searchgroup Selection PHP Page
Group Selection Page PHP & HTML Code
//retrieve our table contents
while($row=mysql_fetch_array($rs)){
extract($row);
//creating new table row per record
echo "<tr>
<td>{$gr_name}</td>
<td>{$gr_leadername}</td>
<td>{$gr_leadcontact}</td>
<td>{$gr_leademail}</td>
<td>";?>Select<?php echo "</td>
</tr>";
}
//end table
echo "</tbody>
</table>
</div>";
}
Select Group javascript function
function select_group( id, name ){
var selvalue = id;
var selvalue1 = name;
window.opener.document.getElementById('gr_id').value = selvalue;
window.opener.document.getElementById('gr_name').value = selvalue1;
if (id!=0) {
window.opener.document.getElementById('div_gr_name').style.display = "inline";
}
else {
window.opener.document.getElementById('div_gr_name').style.display = "none";
}
window.close();
}
if you use window.open you call new browser window which doesnt know nothink about other windows. You can use store your information (cookies or session, i prefer cookies because they are stored on client side) to share across multiple browser windows. If you use phpmyadmin, look how it works

I need to use php variables in javascript/ server-side and client-side conflict

I'm new to programming but I know that you need a server-side language to access a database. I'm using php to access my database and display information, but I need to move the information around on the page at the press of a button (.click) with javascript. So the conversion of data from php to javascript is what is giving me trouble.
Basically, I'm building a system where anyone that buys a ticket is entered in a database. My staff go to a page where the ticket buyers get displayed in a table (Expected Attendance) on the webpage as displayed in a picture I added to the jsfiddle (link in the javascript box), and then they check a box (checkbox) if the person actually comes. At the click of a button (Okay), I need all clicked checkboxes to move to the (
Attending) table on the webpage. Code and fiddle below.
PHP
<?php
//Connect to the database
$mysqli = NEW mysqli('localhost:3306','root','password','roster');
//Query the database
$resultSet = $mysqli->query("SELECT * FROM attendant_info");
//Count the returned rows
if($resultSet->num_rows !=0) {
//Turn the results into an associative array
while($rows = $resultSet->fetch_assoc())
{
$ID = $rows['ID'];
$first_name = $rows['first_name'];
$last_name = $rows['last_name'];
$age = $rows['age'];
$city = $rows['city'];
$state = $rows['state'];
$ticket = $rows['ticket'];
$vip = $rows['vip'];
$entry = "<div id=\"port\"><div id=\"entry\"><!--start of entry-->
<div id=\"ID\"><!--start of ID-->$ID</div><!--end of ID-->
<div id=\"info\"><!--start of info-->
<infowrapper>
<booking><first>First Name:</first><slot1>$first_name</slot1></booking>
<booking><last>Last Name:</last><slot1>$last_name</slot1></booking>
<booking2><age>Age:</age><slot1>$age</slot1></booking2>
<booking4><city>City:</city><slot1>$city</slot1></booking4>
<booking2><state>State:</state><slot1>$state</slot1></booking2>
<booking3><ticket>Ticket#:</ticket><slot1>$ticket</slot1></booking3>
<booking5><vip>VIP:</vip><slot1>$vip</slot1></booking5>
</infowrapper>
<form action=\"\">
Attending<input type=\"checkbox\" name=\"attending\" value=\"attending\">
</form>
</div><!--end of info-->
</div><!--end of entry-->
</div>";
echo "$entry";
}
//Display the results
}else{
echo "No results.";}
?>
Javascript(Jquery)
$(document).ready(function() {
$(".bypass").click(function() {
if ($("#checkbox").click){document.atbox += "entry";
}
});
});
Here is a fiddle so you can see the whole thing together. My html is located in the fiddle, StackOverflow was giving me a hard time posting it.
http://jsfiddle.net/oy81hrtp/1/
This may give you some idea.
Demo:
http://jsfiddle.net/sfohgrvL/1/
HTML:
<div style="border: 1px solid #000; padding:10px">
<h1>Expected Attendance</h1>
<div id="expected_attendance">
<p><input type="checkbox" class="my_checkboxes" />Option1</p>
<p><input type="checkbox" class="my_checkboxes" />Option2</p>
<p><input type="checkbox" class="my_checkboxes" />Option3</p>
<p><input type="checkbox" class="my_checkboxes" />Option4</p>
<p><input type="submit" class="my_submit" /></p>
</div>
</div>
<br></br>
<div style="border: 1px solid #000; padding:10px">
<h1>Attendance</h1>
<div id="attendance">
</div>
</div>
JS:
$(function(){
$(".my_submit").on('click', function(){
ht = $("#attendance").html();
$("input:checkbox[class=my_checkboxes]:checked").each(function()
{
var th = $(this);
ht = ht + th.parent().html();
th.parent().remove();
});
$("#attendance").html(ht);
});
});
To properly check your checkbox, follow this method
$(document).ready(function() {
$(".bypass").click(function() {
if($('#checkbox').prop('checked')) {
//Do what you want
}
});
});

search result not showing in the same window

my search result does not show on the same window, i would want the result to be displayed on the same window. i have found the same question but the code is different from what I'm using so i cant relate to it: Search wont show on same page
scenario 1:
if I put in the action="search_result2.php" - it will redirect the result on the other page
scenario 2:
if i used action="" in this code below, its not doing anything
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").on('click',function() {
var find = $('#find').val();
var field = $('#field').val();
$.post('search_result2.php',{find:find, field:field}, function(data){
$("#results").html(data);
});
return false;
});
});
</script>
</head>
<body>
<div id="container" style="width:auto">
<div id="mainContent">
<h2>Search</h2>
<form name="search" method="post" action="">
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</form>
<div id="results">
</div>
</div>
</div>
</body>
</html>
here is my search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
If you want to load in the same page, without refreshing the page, you'll need to make an ajax request.
If you can reload the page, the php part must be in the same "location" as your original link.
For example if you put that code on the top of the same file with the form (and rename it with a .php extension), it should work (if the php can interpret in that folder).

Categories

Resources