possible to restrict the duplicates in jquery UI autocomplete - javascript

I'm using json autocomplete for filter the text from database in php codeigniter. I wish to filter the duplicate entries like "Apple", "Apple" could possible to show the one entry "Apple". Following code is for used for filtering
$(function() {
$( "#partnumber" ).autocomplete({
source: function(request, response) {
$.ajax({ url: base_url+"/suggest/part",
data: { term: $("#category").val(), brand: $("#brand").val(), pname: $("#partname").val(), partid: $("#partnumber").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
Controller
function part()
{
$term = $this->input->post('term');
$brand = $this->input->post('brand');
$pname = $this->input->post('pname');
$part = $this->input->post('partid');
$sts = 0;
if (strlen($part) < 2) break;
$rows = $this->suggest->part(array('keyword' => $part,'category' => $term, 'brand_name' => $brand,'p_name' => $pname, 'pres_sts' => $sts));
$json_array = array();
foreach ($rows as $row)
array_push($json_array, $row->part_number);
echo json_encode($json_array);
}
Model
function part($options = array())
{
$this->db->select('part_number');
$this->db->like('ctr_name', $options['category']);
$this->db->like('brn_name', $options['brand_name']);
$this->db->like('prt_name', $options['p_name']);
$this->db->like('present_status', $options['pres_sts']);
$this->db->like('part_number', $options['keyword'], 'after');
$query = $this->db->get('partnumber');
return $query->result();
}
please help me for solve this issue. Thanks a lot.

put this before your select $this->db->select('part_number');
$this->db->distinct();

Related

Passing array from JavaScript to PHP without losing code functionality

Using this piece of code I can list all the file URLs inside the Folder_A and Folder_B and Folder_C :
<?php
function getDirContents($directories, &$results = array()){
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
return $results;
}
$directories = array("Folder_A", "Folder_B","Folder_C");
echo json_encode(getDirContents($directories));
And using the JavaScript code below we can log them in the console (And have access to them via javascript):
$(document).ready( function() {
$.ajax({
type: 'POST',
url: '../test.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
console.log(result);
},
});
});
I just want one simple thing that I can't find a solution by myself:
How can I define the Folders inside javascript instead of having them in PHP?
I mean instead of having this inside PHP code:
$directories = array("Folder_A", "Folder_B","Folder_C");
I want to have this in Javascript:
let directories = [ "Folder_A", "Folder_B","Folder_C"];
And return the same functionality.
Pass the directories as part of the data: parameter.
$(document).ready( function() {
let directories = [ "Folder_A", "Folder_B","Folder_C"];
$.ajax({
type: 'POST',
url: '../test.php',
data: {id: "testdata", directories: directories},
dataType: 'json',
success: function(result) {
console.log(result);
},
});
});
Then in PHP you can use $_POST['directories'] to get the array:
echo json_encode(getDirContents($_POST['directories']));

Why Jquery-ui autocomplete is not working in codeigniter?

I am building a blog application. I have a search box which will suggest the categories as user types. So I use jquery-ui autocomplete. But not sure why its not working. I am new to it and spend a whole day. please help. Here is my code.
Model:
public function getCategoriesJson ($keyword) {
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if ($data) {
foreach ($data as $d) {
array_push($output, $d['cat_name']);
}
}
echo json_encode($output);
}
view:
Controller:
public function getCatJson () {
$this->Category_model->getCategoriesJson($this->input->get('query'));
}
Script:
$('#search').autocomplete({
source: '<?php echo base_url(); ?>categories/getCatJson?query=' + $('#search').val(),
minLength: 1
});
Finally, I have got a solution. I changed my model function code and my script like below and it works.
Model:
public function getCategoriesJson($keyword)
{
$this->db->select('cat_name');
$this->db->from('categories');
$this->db->like('cat_name', $keyword);
$data = $this->db->get()->result_array();
$output = array();
if($data)
{
foreach($data as $d)
{
array_push($output, ['label' => $d['cat_name']]);
}
}
echo json_encode($output);
}
Script:
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '<?php echo base_url(); ?>categories/getCatJson',
type:'GET',
dataType: "json",
data: {
query: request.term
},
success: function (data) {
response(data);
},
error: function (message) {
response([{'label': 'Not found!'}]);
}
});
},
minLength: 2
});

highlight the keywords in autocomplete search

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
}
}

jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list

The jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list. Attached image is showing how the result looks like.
HTML:
<form class="navbar-seach pull-center">
<div>
<input type="text" placeholder="Search Productstyle="width:550px; height:40px;padding-left: 10px;margin-top: 20px;" id="searchBox" onkeyup="if (event.keyCode === 13) {searchResults(this.value); this.value = '';}">
</div>
</form>
PHP:
include 'searchbox.php';
$switch_id = filter_input(INPUT_POST, 'switch_id', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($_POST['name_startsWith']))
$searchWordResults = $_POST['name_startsWith'];
else
$searchWordResults = null;
switch($switch_id){
case 1:
$userObj = new searchBox();
echo $userObj->autoComplete($searchWordResults);
break;
}
jQuery:
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "class/searchbox_switch.php",
dataType: "json",
data: { name_startsWith: request.term, switch_id: 1 },
success: function(data) {
response($.map(data, function(item){
return {
label: item.label,
value: item.value
};
}));
},
error: function(response) {
console.log(response.responseText);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
searchResults(ui.item.label);
}
});
PHP (searchbox.php):
include '../dbConnect.php';
class searchBox {
public function autoComplete($name_startsWith) {
$letterSearch = $name_startsWith . "%";
$connectObj = new db_connect();
$dbh = $connectObj->connect();
$stmt = $dbh->prepare("SELECT product_name FROM products WHERE product_name LIKE :start");
$stnd = array();
$stmt->bindParam(':start', $letterSearch, PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}
}
OK got it. You are passing wrong key in your result. Your result data key is "product_name" And You are trying to access "label ". Try This solution:
success: function( data ) {
response( $.map( data, function(item) {
return {
label: item.product_name,
}
}));
},

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;
}
});
});
});

Categories

Resources