Why Jquery-ui autocomplete is not working in codeigniter? - javascript

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

Related

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

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbpost = $result['text'];
}
}
Here is my jQuery function:
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(data);
},
error: function(){
},
});
};
You are not getting anything, because you are not printing/echoing anything.
What happens if you try
foreach($results as $result) {
echo $fbpost = $result['text'];
}
You code is not working because you are not print anything on server side. so you can small change in your code like below.
jsonencode is use to return an array of data.
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
$fbpost = array();
foreach($results as $result) {
$fbpost = $result['text'];
}
echo json_encode($fbpost);
exit;
}
in response you json_encodeed data. You can decode and use this data using below function in response callback.
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(jQuery.parseJSON( data ));
},
error: function(){
},
});
};

Get Success Results From AJAX call

I am trying to get the results from an AJAX call, but I keep getting the error results of the function and I have no idea why.
Here is the javascript:
var curfrndurl = "http://www.website.com/app/curfrnd.php?frndid=" + secondLevelLocation + "&userid=" + items;
$("#loadpage1").click(function(event){
event.preventDefault();
$.ajax({
url: curfrndurl,
dataType: 'json',
type: "GET",
success: function (data){
if (data.success) {
alert("Hi");
$("#curstatus").html(data);
$("#curstatus2").hide();
$("#subtform").hide();
}
else
{
alert("Bye");
$("#curstatus2").html(data);
$("#curstatus").hide();
$("#addform").hide();
}
},
error: function() {
alert('Doh!');
}
});
});
The PHP file is:
<?php
$userdbme = $_GET['userid'];
$frndid = $_GET['frndid'];
$query2 = mysql_query("SELECT * FROM follow WHERE yoozer1='$userdbme' AND yoozer2='$frndid' ORDER BY followid DESC LIMIT 0,1");
$numfriends = mysql_num_rows($query2);
if ($numfriends!=0)
{
echo json_encode(array(
'success' => true
//'user_name' => $userdb
));
echo "<h4>Current Friends</h4>";
}
else {
echo json_encode(array('success' => false));
echo "<h4>Not Friends</h4>";
}
?>
Any help would be greatly appreciated! Thanks!
If you want to echo JSON data, then you need to make sure you don't echo anything else before or after the data.
echo json_encode(array(
'success' => true
));
echo "<h4>Current Friends</h4>";
This is not parsable as JSON, because of the "extra" stuff after the JSON data. Try this:
echo json_encode(array(
'success' => true,
'html' => "<h4>Current Friends</h4>"
));
Then you can do: $("#curstatus").html(data.html);

possible to restrict the duplicates in jquery UI autocomplete

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

double json response

I don't know why this double json response are not successful:
[{"first_content":"content",...}][{"second_content":"content",...}]
So i am getting the message Oops! Try Again.
if(isset($_GET['start'])) {
echo get_posts($db, $_GET['start'], $_GET['desiredPosts']);
echo get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
loadMore.click(function () {
loadMore.addClass('activate').text('Loading...');
$.ajax({
url: 'profile.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function (responseJSON, responseJSON1) {
alert(responseJSON);
loadMore.text('Load More');
start += desiredPosts;
postHandler(responseJSON, responseJSON1);
},
error: function () {
loadMore.text('Oops! Try Again.');
},
complete: function () {
loadMore.removeClass('activate');
}
});
});
What is the solution to get a double json response ? With one there is no problem
"Double JSON response" as you call them is basically invalid JSON. You should have something like so:
{"first_content":"content", "second_content":"content",...}
Or as a couple of people mentioned:
[{"first_content":"content",...}, {"second_content":"content",...}]
You probably need to modify some server side code, your get_posts function could return a PHP array instead of a JSON array. Example:
function get_posts(){
$array = array('content' => 'foo', 'title' => 'bar');
return $array;
}
Then in your profile.php:
if(isset($_GET['start'])) {
$posts = get_posts($db, $_GET['start'], $_GET['desiredPosts']);
$posts1 = get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
echo array($posts, $posts1);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}

Categories

Resources