google style autocomplete with arrow keys - javascript

i created a simple search engine that displays mysql database results using the php "LIKE" function (code below). everything works fine. i would just like to make it so that when the user starts typing he/she can use the arrow keys to scroll down and press enter on an item just like google. thanks. my code:
HTML:
<input type="text" name='search' id="searchbooks" onkeyup='getbooks(this.value);' value="search" onblur="setTimeout('removedrop()', 80);">
<div id='drop'></div>
JAVASCRIPT:
function getbooks(value){
if (value!=""){
$.post('getbooks.php', {book: value},
function (data) {
$('#drop').html(data);
doCSS();
});
}
else {
$('#drop').html("");
undoCSS();
}
}
getbooks.php file:
<?php
include 'connect.php';
$book=mysql_real_escape_string(addslashes($_POST['book']));
$result=mysql_query("SELECT * FROM searchengine WHERE title LIKE '$book%'");
while ($row=mysql_fetch_assoc($result)){
$title=$row['title'];
$id=$row['id'];
echo "<div id='link'><a href='index.php?id=$id' id='words'>". $row['title'] ."</a></div>";
}
?>

How about using the jQuery autocomplete plugin? It's made for exactly this use case.

Related

How to call a function in a php file using jquery load?

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>
Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

JQuery: Post variable to the second file, and when the enter key pressed, the web will direct me to the first search result page

I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)

Using auto complete textbox get table record from mysql database and shows in text fields

I need to access the table record from the database when they press enter in the autocomplete textbox (at the time of select value), and it shows data in text element.
I have tried this code but cannot get the whole record:
html code:
<input class="form-control" name="sel_product_name" id="sel_product_name" >
<input class="form-control" name="sel_product_id" id="sel_product_id">
javascript code:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_product_name").autocomplete({
source:'autocomplete.php',
minLength:1
});
});
</script>
autocomplete.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("es_restaurant");
$term=$_GET["term"];
$query=mysql_query("SELECT fld_product_id,fld_product_name
FROM tbl_product_master_header
where fld_product_name like '%".$term."%' ");
$json=array();
while($product_name=mysql_fetch_array($query))
{
$json[]=array(
'value'=> $product_name["fld_product_name"]
//I want to add one more column value to display fld_product_id in
//another text box
);
}
echo json_encode($json);
?>
Try hanging the code to this:
$json = array();
while($product_name=mysql_fetch_array($query)) {
$json[]= $product_name["fld_product_name"];
}
echo json_encode($json);
I think because you are adding another layer to the array it is not working.
http://jqueryui.com/autocomplete/ shows using an array without keys.
http://www.smarttutorials.net/jquery-autocomplete-search-using-php-mysql-and-ajax/ also confirms this.
As to your comment try this:
while($product_name=mysql_fetch_array($query)) {
$json[]= array('id' => $product_name["fld_product_id"],
'value' => $product_name["fld_product_name"]);
}
http://www.simonbattersby.com/blog/jquery-ui-autocomplete-with-a-remote-database-and-php/

Javascript LinkedIn API Sign In Issues

I am trying to create a form that grabs values from the user's LinkedIn profile in order to make it easier to sign on. I am having trouble grabbing some of the fields.
When I try to auto populate my form I have no issues grabbing First Name, Last Name, LinkedIn ID, and Headline. When I try to grab other fields like location, previous jobs, and industry and error appears on the page (ie. "Error: industry is not defined"). Note: this application has full profile privileges. I have attached snippets of my code and the results in the links below. Any advice would be greatly appreciated.
Working Code:
http://i.imgur.com/hX9fBQh.png
Non Working Code (added industry field):
http://i.imgur.com/PqMd1zj.png
Here is the code that is working
<script type="IN/Login">
<input type="text" value="<?js= firstName ?>" />
<input type="text" value="<?js= id ?>" />
</script>
In below script use ID that is available from above script
<script type="IN/MemberData"
data-ids="`here_put_the_ID`"
data-fields="firstName,lastName,industry">
<ul>
<?js for (var member in $("*")) { ?>
<li><?js= $(member).firstName ?> <?js= $(member).lastName ?>
Industry : <?js= $(member).industry ?></li>
<?js } ?>
</ul>
</script>
the second way is to get information is
function callmeOnLoad(){
IN.API.Profile("me")
.fields("id", "firstName", "lastName", "pictureUrl", "publicProfileUrl","industry")
.result(function(result, metadata) {
setConnections(result.values, metadata);
});
}
function setConnections(connections) {
for (id in connections) {
console.log(connections[id].firstName+":"+connections[id].industry)
}
}

Separating variables for SQL insert using PHP and JavaScript

A grid table is displayed via PHP/MySQL that has a column for a checkbox that the user will check. The name is "checkMr[]", shown here:
echo "<tr><td>
<input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\"
data-info=\"{$Row[BOL_NUMBER]}\" data-to=\"{$Row[TO_NUMBER]}\"
name=\"checkMr[]\" />
</td>";
As you will notice, there is are attributes for id, data-info, and data-to that are sent to a modal window. Here is the JavaScript that sends the attributes to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
var selectedBL = [];
var selectedTO = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
selectedBL.push($(this).attr('data-info'))
selectedTO.push($(this).attr('data-to'))
});
$(".modal-body .containerNumber").val( selectedID );
$(".modal-body .bolNumber").val( selectedBL );
$(".modal-body .toNumber").val( selectedTO );
});
});
</script>
So far so good. The modal retrieves the attributes via javascript. I can choose to display them or not. Here is how the modal retrieves the attributes:
<div id="myModal">
<div class="modal-body">
<form action="" method="POST" name="modalForm">
<input type="hidden" name="containerNumber" class="containerNumber" id="containerNumber" />
<input type="hidden" name="bolNumber" class="bolNumber" id="bolNumber" />
<input type="hidden" name="toNumber" class="toNumber" id="toNumber" />
</form>
</div>
</div>
There are additional fields within the form that the user will enter data, I just chose not to display the code. But so far, everything works. There is a submit button that then sends the form data to PHP variables. There is a mysql INSERT statement that then updates the necessary table.
Here is the PHP code (within the modal window):
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
$to = $_POST['toNumber'];
if(isset($_POST['submit'])){
$bol = mysql_real_escape_string(stripslashes($bol));
$container = mysql_real_escape_string(stripslashes($container));
$to = mysql_real_escape_string(stripslashes($to));
$sql_query_string =
"INSERT INTO myTable (bol, container_num, to_num)
VALUES ('$bol', '$container', '$to')
}
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Saved')
</script>");
}
else{
echo ("<script language='javascript'>
window.alert('Not Saved')
</script>");
}
?>
All of this works. The user checks a checkbox, the modal window opens, the user fills out additional form fields, hits save, and as long as there are no issues, the appropriate window will pop and say "Saved."
Here is the issue: when the user checks MULTIPLE checkboxes, the modal does indeed retrieve multiple container numbers and I can display it. They seem to be already separated by a comma.
The problem comes when the PHP variables are holding multiple container numbers (or bol numbers). The container numbers need to be separated, and I guess there has to be a way the PHP can automatically create multiple INSERT statements for each container number.
I know the variables need to be placed in an array somehow. And then there has to be a FOR loop that will read each container and separate them if there is a comma.
I just don't know how to do this.
When you send array values over HTTP as with [], they will already be arrays in PHP, so you can already iterate over them:
foreach ($_POST['bol'] as $bol) {
"INSERT INTO bol VALUES ('$bol')";
}
Your queries are vulnerable to injection. You should be using properly parameterized queries with PDO/mysqli
Assuming the *_NUMBER variables as keys directly below are integers, use:
echo '<tr><td><input type="checkbox" value="'.json_encode(array('CONTAINER_NUMBER' => $Row[CONTAINER_NUMBER], 'BOL_NUMBER' => $Row[BOL_NUMBER], 'TO_NUMBER' => $Row[TO_NUMBER])).'" name="checkMr[]" /></td>';
Then...
$('a#specifyAnchor').click(function() {
var selectedCollection = [];
$(':checkbox[name="checkMr[]"]:checked').each(function() {
selectedCollection.push($(this).val());
});
$(".modal-body #checkboxCollections").val( selectedCollection );
});
Then...
<form action="" method="POST" name="modalForm">
<input type="hidden" name="checkboxCollections" id="checkboxCollections" />
Then...
<?php
$cc = $_POST['checkboxCollections'];
if (isset($_POST['submit'])) {
foreach ($cc as $v) {
$arr = json_decode($v);
$query = sprintf("INSERT INTO myTable (bol, container_num, to_num) VALUES ('%s', '%s', '%s')", $arr['BOL_NUMBER'], $arr['CONTAINER_NUMBER'], $arr['TO_NUMBER']);
// If query fails, do this...
// Else...
}
}
?>
Some caveats:
Notice the selector I used for your previous $('a').click() function. Do this so your form updates only when a specific link is clicked.
I removed your mysql_real_escape_string functions due to laziness. Make sure your data can be inserted into the table correctly.
Make sure you protect yourself against SQL injection vulnerabilities.
Be sure to test my code. You may have to change some things but understand the big picture here.

Categories

Resources