highlight the keywords in autocomplete search - javascript

i want to highlight the keywords according to its autocomplete search, like if i type a then the results it gives:
java
javascript
so in this java
javascript
and then if i type av then java
javascript should get highlight or bold according to the search.
Below is my code:
javascipt
$(this).ready( function() {
$("#id").autocomplete({
minLength: 1,
source:
function(req, add){
//alert("xdhf");
$.ajax({
url: "<?php echo base_url(); ?>/trainer_dashboard/autocomplete_batchsearch",
data: req,
dataType: 'json',
type: "post",
cache: false,
success: function (data){
//alert(data);
if(data.response =="true"){
add(data.message);
console.log(data);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
});
},
});
});
controller
public function autocomplete_batchsearch()
{
//$user_id=get_cookie('trainer_login_user_id');
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->trainer_dashboard_model ->batchsearch($keyword); //Search DB
//echo"";print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->id,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('trainer_dashboard_view',$data); //Load html view of search results
}
}

Related

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

Jquery Autocomplete using codeigniter not showing on view

Javascript Code
$( "#cusname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: base_url+'admin/auto_cusname',
data: { term: $("#cusname").val()},
dataType: "json",
type: "GET",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 1
});
Controller
public function auto_cusname(){
$term = $this->input->get('term');
if (isset($term)){
$result = $this->mod_admin->autocusname($term);
}else{
$data['error'] = $term;
$this->load->view('error', $data);
}
print json_encode($result);
}
Model
public function autocusname($search_term) {
$this->db->select('Firstname');
$this->db->like('Firstname', $search_term);
$response = $this->db->get($this->tbl_costumer,$this->uri->segment(2))->result_array();
// var_dump($response);die;
return $response;
}
View
<div class="ui-widget">
<input id="cusname" name="cusname" placeholder="Customer Name"/>
</div>
My problems is when i try to query it on the browser i got this
localhost/PPDOIMS/admin/auto_cusname?term=s
it outputs the data
[{"Firstname":"Crisa"},{"Firstname":"Thomas "}]
but when try to view it on my page and type something i got no response.
is there something wrong on my code?

ajax jquery always running Error;

Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.

jQuery autocomplete ajax request not displaying returned data

When I see on the debug developer tool ajax request responded with data but the data is not rendered in the text box. The data contains some special characters as you can see in the picture.
What is exactly wrong with the response function ? What (like utf-8 encoding maybe) should I add to the ajax call to display the special character ?
html:
<select name="selCat">
<option>....</option>
</select>
<input class="col-3" type="text" id="txtPOI" name="txtPOI" />
jquery:
$("#txtPOI").autocomplete({
source: function(request, response) {
$.ajax({
url: '<?php echo site_url("crowd/get_POIs") ?>',
data: {cat: selectedCode, q: request.term},
dataType: "json",
type: "post",
success: function(data) {
response(data);
},
fail : function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},minLength: 3
});
}
});
Controller :
function get_POIs(){
$cat = $this->input->post('cat');
$q = $this->input->post('q');
//echo $cat;
if (isset($cat) && isset($q)){
$cat = strtolower($cat);
$q = strtolower($q);
$data=$this->crowd->get_POIs($cat,$q);
//echo "aa";
$a_json = array();
if(count($data) > 0){
foreach ($data as $row){
$a_json_row["title"] = $row->title;
$a_json_row["contentid"] = $row->contentid;
$a_json_row["latitude"] = $row->latitude;
$a_json_row["longitude"] = $row->longitude;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
}
}
}
Model :
function get_POIs($cat, $q){
$this->db->DISTINCT();
$this->db->select('title, a.contentid, latitude, longitude, address');
$this->db->from('attraction a');
$this->db->join('geographicdata g', 'a.contentid = g.contentid', 'left');
$this->db->where('cat3 = "'.$cat.'"');
$this->db->where('title like "%'.$q.'%"');
$this->db->order_by('title','ASC');
$query = $this->db->get()->result();
//die(var_dump($query));
//echo $this->db->get_compiled_select();
return $query;
}
I managed to solve this problem by modifying the code inside the success event. Here how I did it.
change from
success: function(data) {
response(data);
}
to
success: function(data) {
response( $.map( data, function( item )
{
return{
label: item.title,
value: item.title,
contentid: item.contentid,
latitude: item.latitude,
longitude: item.longitude
}
}));
}

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources