bootstrap typeahead is not fetching results - javascript

i am trying to autocomplete using bootstrap typeahead but its not fetching results.
i tried many times using jquery,ajax
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="typeahead.js"></script>
<script>
$(function() {
$('#typeahead').typeahead({
source:function(typeahead,query)
{
$.ajax({
url :'mysql.php',
type :'POST',
data :'query=' + query,
dataType :'json',
async :false,
success:function(data)
{
typeahead.process(data);
}
});
}
});
});
</script>
</head>
<body>
<input type="text" name="term" id="typeahead" class="form-control" size="50" placeholder="Search" >
</body>
</html>
mysql.php
<?php
$conn = mysqli_connect('localhost', 'root','','mydb');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$searchTerm = $_POST['query'];
$query = mysqli_query($conn,"SELECT * FROM content_ref_table WHERE title LIKE '%{$searchTerm}%' ORDER BY title ASC");
while ($row = mysqli_fetch_assoc($query)) {
$data[] = $row['title'];
}
echo json_encode($data);
?>
i am using typeahead along with ajax call,but its not giving results

I believe you are using bootstrap3-typeahead / or another bootstrap 2.x typeahead deriviation? If so, you have messed up the arguments for the source method - it should be process, query where process is the async callback. Your code could be reduced to
$('#typeahead').typeahead({
source: function(query, process) {
var url = 'mysql.php?query=' + query
return $.get(url, {}, function(data) {
return process(data)
})
}
})

Related

Sending Post request by ajax to PHP page from select box

I've trying to set up a Question/Answer system and I've encountered with a couple of errors while setting up dependent select boxes
I wanna send the information of masters select box (Maters'id) to PHP file (DB.PHP) to handle a group of actions.
HTML Page
<?php
require_once "DB.php";
require_once "functions.php";
require_once "stuQuestion.php";
if(! isset($_SESSION['student'])){
redirect("stulogin/login.php");
die;
}
$date = userGets($connection , "students_questions" , $_SESSION['students_id']);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#masters').on('change',function() {
var mid = $('#masters').val();
$.ajax({
url: 'DB.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: 'mid=' + mid
}).done(function(user){
console.log(user);
user = JSON.parse(user);
$('#topics').empty();
user.forEach(function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
})
})
</script>
</head>
<select class="form-control" id="masters" name="masters" >
<option selected disabled>Choose Master</option>
<?php
//id='".$master['id']."' value = '".$master['id']."'
foreach($date as $master)
{
echo "<option id='".$master['id']."' value = '".$master['id']."'> ".$master['master']."</option>";
}
?>
</select>
<select class="form-control" id="topics" name="topics">
</select>
DB.php
function connectToDB() {
try {
$connect = new PDO("mysql:host=127.0.0.1;dbname=university","root","");
$connect->exec("set character set utf8");
$connect->exec("set names utf8");
$connect->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);
return $connect;
}
catch (PDOException $e)
{
die($e->getMessage());
} }
$connection = connectToDB();
if(isset($_POST['mid'])){
$statment = $connection->prepare("SELECT topic FROM students_questions
WHERE user_id = " . $_POST['mid']);
$statment->execute();
$user = $statment->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($user) ;
}
else
var_dump("No Request");
function userGets($conn , $table , $user_id = null) {
$statment = $conn->prepare("SELECT DISTINCT master FROM {$table} WHERE
user_id = :user_id");
$statment->bindParam("user_id" , $user_id );
$statment->execute();
$master = $statment->fetchAll(PDO::FETCH_ASSOC);
return $master ? $master : false;
}
When I log in and redirect to stuIndex.php (The page which contains select boxes)I will encounter with "No Request"! and after 3 days hunting around for probable correct answers, I couldn't solve it so far:(
Thanks in advance for any help you are able to provide.
PS: if someone needs more information, please tell me I will send the complete source code or sharing more information.
Too many jQuery and bootstrap libraries and they are HTTPS and HTTP versions from different CDNs
Syntax error in data :
No need for parsing the JSON since it is default
No error handling for the request. If you do not want error handling do this
$(function() {
$('#masters').on('change', function() {
var mid = this.value;
if (val) {
$.post('DB.php', {"mid": mid}, function(user) {
$('#topics').empty();
$.each(user,function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
}
})
})
using
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/popper.min.js"></script>

Autocomplete using typeahead.js (JSON string from database) - how to add additional var?

Im trying to make an autocomplete selector (typeahead.js) with JSON.
Now i got working code - i can start typing and i got autocomplete but i got only "Name Surname - Company Name" displayed.
What should i do if i would like to get an additional info like ID of that company from database? How can i pass that var through JSON and somehow pass to html form?
Working code:
HTML:
<div class="form-group">
<label for="exampleInput">User</label>
<input type="text" id="user" name="user" size="30" class="user form-control typeahead" placeholder="User">
</div>
JS:
<script type="text/javascript">
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get('helpers/szukaj_uzytkownika.php', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
return process(data);
});
}
});
</script>
Server-side:
<?php
include ('../db.php');
$sql = "SELECT * FROM users WHERE company_name LIKE '%".$_GET['query']."%' OR person_name LIKE '%".$_GET['query']."%' OR person_surname LIKE '%".$_GET['query']."%'LIMIT 10";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[] = $row['person_name']." ".$row['person_surname']." - ".$row['company_name'];
}
echo json_encode($json);
?>
I will appreciate any help. Thank you in advance.
Server-side:
<?php
include ('../db.php');
$sql = "SELECT * FROM users WHERE company_name LIKE '%".$_GET['query']."%' OR person_name LIKE '%".$_GET['query']."%' OR person_surname LIKE '%".$_GET['query']."%'LIMIT 10";
$result = $mysqli->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json['name'] = $row['person_name']." ".$row['person_surname']." - ".$row['company_name'];
$json['id] = $row['id'];
}
echo json_encode($json);
?>
JS
<script type="text/javascript">
$('input.typeahead').typeahead({
source: function (query, process) {
return $.get('helpers/szukaj_uzytkownika.php', { query: query }, function (data) {
console.log(data);
data = $.parseJSON(data);
var id = data.id;
return process(data.name);
});
}
});

Ajax request working but no output

Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}

ajax jquery form fetching mysql data

I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>

PHP Ajax not creating post variable

A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});

Categories

Resources