Struggling with typeahead.js - javascript

I'd appreciate some help in getting a simple demo working of the Twitter typeahead.js library as I've struggled with it over the last two days.
I'm using a MAMP development server on my Macbook, and have a (large) MySQL database table that I'd like to query to use with a typeahead field on a Web page.
This is my main HTML file that I'm using. It literally has one field in it.
type-ahead.php
<?php
// HTML5 Header stuff
echo '<!DOCTYPE html>'.PHP_EOL;
echo '<html>'.PHP_EOL;
echo '<head><meta charset="UTF-8">'.PHP_EOL;
echo '<title>Typeahead Example</title>'.PHP_EOL;
// include the two libraries for typeahead to work
echo '<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '</head>'.PHP_EOL;
echo '<body>'.PHP_EOL;
echo '<h2 class="myclass">Typeahead testing</h2>'.PHP_EOL;
echo 'Type in a search: <input type="text" name="user_search">'.PHP_EOL;
echo "<script type='text/javascript'>".PHP_EOL;
echo "$('#user_search').typeahead({".PHP_EOL;
echo " name: 'user_search',".PHP_EOL;
echo " remote: './type-ahead-ajax.php?query=%QUERY',".PHP_EOL;
//echo " minLength: 3,".PHP_EOL;
//echo " limit: 10".PHP_EOL;
echo "});".PHP_EOL;
echo "</script>".PHP_EOL;
echo '</body></html>'.PHP_EOL;
?>
The source of this from the browser looks OK, but I'll paste it here too just in case.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Typeahead Example</title>
<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>
</head>
<body>
Type in a search: <input type="text" name="user_search">
<script type='text/javascript'>
$('#user_search').typeahead({
name: 'user_search',
remote: './type-ahead-ajax.php?query=%QUERY',
});
</script>
</body></html>
I've tested my call back script separately, and it is definitely connecting to the database and pulling back some results. For example if I use '/type-ahead-ajax.php?query=bleach' as a URL, I get all the products containing the word 'bleach'
type-ahead-ajax.php
<?php
// Connect to the database
try {
$dbh = new PDO('mysql:host=localhost; dbname=menu;', 'root', 'root');
$query = '%'.$_GET['query'].'%'; // add % for LIKE query later
//$query = '%milk%'; //debug
echo $query.PHP_EOL;
// do query
$stmt = $dbh->prepare('SELECT title FROM waitrose WHERE title LIKE :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();
// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$results[] = $row;
echo strtolower($row).PHP_EOL; //debug
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// and return to typeahead
return json_encode($results);
?>
Basically, when you type into the input field nothing happens. It's as though either the callback isn't being called, it's returning nothing, or it's not registered properly in the first place.
Any suggestions?

When you do $('#user_search'), you're referring to an element with id user_search. You haven't, however, given your input any id. Add it:
<input type="text" name="user_search" id="user_search">
If that doesn't work, make sure you get the data you assume by accesssing ./type-ahead-ajax.php?query=%QUERY manually with some query, and check for JavaScript errors in your browser console.

Related

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

actual code for xferring javascript variable to post variable

I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);

PHP doesn't output error from mysql query for non-existent rows for autocomplete

I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.

Inserting value in a JavaScript variable from php code

I am trying to test the following code for inserting the value from PHP code to my javascript variable x
tested the PHP code, and it's giving the correct output but the alert box in the javascript shows this -
date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000"; $query = mysql_query($myquery); if ( ! $myquery ) { echo mysql_error(); die; } $data = array(); for ($x = 0; $x < mysql_num_rows($query); $x++) { $data[] = mysql_fetch_assoc($query); } //echo json_encode($data); echo ''; mysql_close($server); ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing </title>
<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
</head>
<body>
<?php
$username='user';
$password='pass';
$host='xx.xx.xx.xx';
$database='abc';
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = 'select code a,sum(fee) b from xyz where date > date_sub(curdate(),interval 1 day) and activity=1 group by code having b > 1000';
$query = mysql_query($myquery);
if ( ! $myquery ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
//echo json_encode($data);
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
mysql_close($server);
?>
<script type="text/javascript">
function test(){
var x = document.getElementById("myPhpValue").value;
alert(x);
}
test();
</script>
</body>
</html>
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
Then:
var x = document.getElementById("myPhpValue").value;
you need to insert id="myPhpValue", because you used the "getElementById";
Add ID attribute in the html line
echo '<input type="hidden" name="myPhpValue" value="'. json_encode($data) . '">';
replace the above line by
echo '<input type="hidden" name="myPhpValue" id ="myPhpValue" value="'. json_encode($data) . '">';
You are inserting a value into html, not javascript code.
Do it like that:
<script type="text/javascript">
function test(){
var x = <?php echo json_encode($data); ?>;
alert(x);
}
test();
</script>
Server configuration problems
If You are getting php code on client-side (view-source to confirm), then the PHP engine is not working on the server.
You should check that php is properly installed on the server and is set as a handler for php files in your web server.
This depends on your web server and operating system.
Code problems
Problem #1: your output (echo) is creating an HTML element, not javascript. Hence you should escape the content for HTML - use htmlspecialchars instead of json_encode
Problem #2: you access the element with javascript document.getElementById but your actual element does not have an ID. Hence need to add the id attribute to your html input element.
Solution:
Stage 1: php outputs html - use htmlspecialchars and add id attribute
echo '<input type="hidden" name="myPhpValue" id="myPhpValue" value="'. htmlspecialchars($data) . '">';
Stage 2: javascript accesses html element (this is taken as-is from your code).
var x = document.getElementById("myPhpValue").value;
Side-note
You're using a deprecated mysql extension and should switch to PDO or mysqli instead.
There are numerous discussions both on SO and external resources on the matter.
Just a few:
Choosing an API - PHP manual
What is the difference between MySQL, MySQLi and PDO?
mysqli or PDO - what are the pros and cons?

jQuery with PHP&MySQL autocomplete cannot work

Study jQuery from online tutorial, find many tutorials, just find one simple maybe good for newbie.
Here is the code for index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>
Autocompletement
</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="suggest.js"></script>
</head>
<body>
<input type="text" name="suggest" placeholder="Type a Country Name..." onkeyup="suggestion()"/>
<div id="autosuggest"></div>
</body>
</html>
Here is the code for suggest.php:
<?php
include "connect.php";
function auto($data){
global $mysqli;
$data = $_GET['data'];
$query = "SELECT code, name_en
FROM countries
WHERE name_en LIKE '%$data%'
OR code LIKE '%$data%'";
$items = '<ul class="suggestion">';
if($result = $mysqli->query($query)){
/* fetch associative array */
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
$items .= '</ul>';
}else{
$items = "No results Found...";
}
echo $items;
}
auto();
?>
Here is the code for suggest.js
function suggestion(){
var suggestVal = $('#suggest').val();
if(suggestVal != ''){
$.ajax({
url: 'suggest.php?data='+suggestVal,
success: function(data){
$('#autosuggest').html(data);
}
})
}
}
The result above will only show "No results Found...", it seems that processing file suggest.php is not working, then I test it with a test file test.php:
$mysqli = new mysqli("host","user","pass","database");
//auto();
$data = $_GET['input'];
//$data = "ca";
$query2 = "SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'";
echo "<br>" .$query2;
echo "<br>";
if($mysqli){
echo "Yes SQL";echo "<br>";
}else{
echo "No SQL";echo "<br>";
}
$result = $mysqli->query("SELECT code, name_en FROM countries WHERE name_en LIKE '%$data%' OR code LIKE '%$data%'");
if($result->num_rows){
echo "Yes Result";echo "<br>";
}else{
echo "No Result";echo "<br>";
}
The weird thing is that I cannot find anything wrong with my code, checked php.net sample and seems all to be good? But when I check vam_dump($result) then it is "null", any helps will appreciated.
Here is the test.php output:
SELECT code, name_en FROM countries WHERE name_en LIKE '%ch%' OR code LIKE '%ch%'
Yes SQL
No Result
URL: http://IP/project/jquery/auto_diy/test.php?input=ch
You defined your function as having a $data argument
function auto($data){...}
but you are calling it without the argument,
auto();
this will trigger a notice.
The argument is not needed, since you are already using $data=$_GET['data']; inside your function.
Then in your ajax call you should change it like so
$.ajax({
url: 'suggest.php',
type: 'get', // this can be omitted because GET is default
data: 'data='+suggestVal, // or
// data: {data:suggestVal}
success: function(data){
$('#autosuggest').html(data);
}
})
Update:
in test.php output directly the value of $result->num_rows
print "Rows returned: " . $result->num_rows . "<br>";
if you get zero rows, copy the query and run it in phpmyadmin or a mysql console to verify the data.
in suggest.php, update this:
$result = $mysqli->query($query);
if (!$result) {
print 'Could not execute query';
}
else {
while($row = $result->fetch_assoc()){
$items .= '<li>'.$row['name_en'] . ' ' . $row['code'].'</li>';
}
}
$items .= '</ul>';

Categories