Auto complete not showing result jquery - php

I am trying to create an auto complete using jqueryui.I am echo ing a database result from the remote file search.php.It is showing the correct word in the response of fire bug but the suggetion list is not at all showing in my html page.
Can anybody please help me?
i'm using the code of multipile ,remote demo in the jqueryui.com
my php code
<?php include("connection.php");
$q=mysql_real_escape_string($_GET['term']);
$x="select fieldname from tablename where fieldname like '$q%'";
$query=mysql_query($x);
while($row=mysql_fetch_array($query)) { echo $row['fieldname']."\n"; } ?>
========================================================================
------------------------------------------------------------------------
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#birds" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>

If your remote file is placed on different domain you have to use JSONP.
JSON dosen't support cross-domain data transfer.
Read more about Same Origin policy

Related

jQuery autocomplete text seperated with comma not working in CodeIgniter

code: search_json.php
<?php
function get_data()
{
$ci =& get_instance();
$ci->db->select('*');
$ci->db->from('top_menu');
$ci->db->order_by('menu_name');
$query = $ci->db->get();
$result = $query->result_array();
foreach($result as $row)
{
$menu[] = array(
'id' => $row["id"],
'label' => $row["menu_name"]
);
}
return json_encode($menu);
}
echo "<pre>";
print_r(get_data());
echo "</pre>";
?>
index.php
<script>
$(function(){
function split( val )
{
return val.split( /,\s*/ );
}
function extractLast( term )
{
return split( term ).pop();
}
$( "#tags" )
.on( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "<?php echo base_url(); ?>user/search", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags</label>
<input type="text" class="form-control1" id="tags" name="tags"/>
</div>
controller: user.php
public function search()
{
$this->load->view('user/search_json');
}
In this code, I have created a json format file (i.e. search_json.php) and I want to implement it inside index.php. search_json.php file works perfectly, data is in proper format, but when I write something inside the tags input field it shows nothing. So, how can I fix this issue?
Thank you!
First of all, <?php echo base_url(); ?>user/search can, and should be used like <?php echo base_url('user/search'); ?>. (I mostly do <?= base_url().'user/search'; ?> though :) Funny to see I'm not the only one using it 'wrong'...
If I have ajax controllers I tend to set the output like this:
$this
->output
->set_content_type('application/json')
->set_output(json_encode($return)); // Where $return is an array
So in your case I guess you should load the json php file as a partial and set the output to the partial contents:
public function search() {
$return = $this->load->view('user/search_json', '', true);
$this
->output
->set_content_type('application/json')
->set_output($return);
}

Codeigniter Autocomplete search box with JSON, MySql

I'm trying to make a autocomplete search box but this code doesn't work, I'm trying this for three days. I need an autocomplete search result system. I have tried a several ways. but in my view, I don't get any response or any error. after typing one letter it doesn't tell anything
code on controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('search');
}
public function getFunction()
{
if ( !isset($_GET['term']) )
exit;
$term = $_REQUEST['term'];
$data = array();
$rows = $this->model_search->getData($term);
foreach( $rows as $row )
{
$data[] = array(
'label' => $row->bname.', '. $row->bname,
'value' => $row->bname);
}
echo json_encode($data);
flush();
}
}
and model code is
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_search extends CI_Model {
public function __construct()
{
parent::__construct();
// Your own constructor code
}
function getData($term)
{
$sql = $this->db->query('select * from brands where bname like "'. mysql_real_escape_string($term) .'%" order by bname asc limit 0,10');
return $sql ->result();
}
}
view code is;
<html lang="en-US">
<head>
<title>Codeigniter Autocomplete</title>
<link rel="stylesheet" href="<?php echo base_url('assets/css/jquery-ui.css'); ?>" type="text/css" media="all" />
<script src="<?php echo base_url('assets/js/jquery-ui.js'); ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/js/jquery-1.8.3.js'); ?>" type="text/javascript"></script>
<meta charset="UTF-8">
<script type="text/javascript">
$(document).ready(function(){
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#txtinput" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "<?php echo base_url();?>search/getFunction",{
term: extractLast( request.term )
},response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
return false;
}
});
});
});
</script>
</head>
<body>
<input type="text" id="txtinput" size="20" />
</body>
</html>

how to pass hidden id using json in jquery ui autocomplete?

perhaps it is duplicate,but i can't found solution so i posted this question.I am use jquery ui for auto complete search box. it works fine but the problem is i want to search using id.example:when user type paris,i try to send city_id in mysql for search. so problem is how to pass hidden id with json?
here the code:
<input type="text" name="grno" id="grno" class="input" title="<?php echo $lng['vldgrno'];?>
jquery code:
<script>
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#grno" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "ui-autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "pages/search.php", {
term: extractLast( request.term )
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( "," );
alert(data.id);
return false;
}
});
});
</script>
autocomplete.php :
<?php
mysql_connect('localhost','root','');
mysql_select_db('school');
$return_arr = array();
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
//create select query
$query = "select `grno`,`first_name`,`student_id` from `tbl_student` where `grno` like '%".$term."%' or `first_name` like '%".$term."%'";
// Run the query
$result = mysql_query ($query);
$array = array();
while($obj = mysql_fetch_array($result)){
$array['name'] = $obj['first_name']."(".$obj['grno'].")";
array_push($return_arr,$obj['first_name']."(".$obj['grno'].")");
}
$json = json_encode($return_arr);
echo $json;
?>
so.how to pass student_id in autocomplete.php,like label and value.{label='xyz' value='1'}
In autocomplete.php replace this code
array_push($return_arr,array("value"=>$obj['student_id'],"label"=>$obj['first_name']."(".$obj['grno'].")"));
and in your script change this
terms.push( ui.item.label );
$( "#stud_id" ).val( ui.item.value );
hope,this is what you find.

How to Save Multiple Values in jQuery Autocomplete to MySQLi DB?

I'm just learning about the jQuery AutoComplete Widget. The values pop up with a comma nicely. So, the visual display to the user is great.
My issue is how do I save the multiple values to a MySQLi database?
Here is the code:
<script>
$(function() {
var availableskills = [
"ActionScript",
"AppleScript",
..........
more languages
"XML"
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
$( "#skills" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
// could have source as a "url"
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableskills, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
Now, here's my input id for letting the user select the skills:
<div class="ui-widget">
<!--<label for="skills">Tag programming languages: </label>-->
<input type="text" id="skills" size="50" />
</div>
Not sure on how to save the skills the user selects into a database. I can save data to a MySQLi db with ease; the issue is how can I take say three skills and save them into three different rows in a table in a database.
Any help, very much appreciated.
Ken
for example you will do form post with the input name skills
<form method="post" action="test.php">
<div class="ui-widget">
<input type="text" id="skills" size="50" name='skills' />
</div>
</form>
then test.php would be something like
<?php
//...do some mysql connections
$skills = explode(",",$_POST['skills']);
foreach($skills as $skill){
$statement.="INSERT INTO blahblahblah SET skill = ".mysqli_real_escape_string($skill);
}
$mysqli->multi_query($statement);

JQuery GET works only first time, second time I just get server response... why?

I have some JQuery where when you click on a "Add to Basket" button (it's really a link), the first time everything works as expected however click the button a second time, although the product is added to basket (database row has increased quantity), the response sent by server is outputted rather than "captured" by JQuery in the SUCCESS function.
I don't understand why this would happen, any thoughts on this?
JQuery
$(function() {
$( '.button' ).click(function( e ) {
e.preventDefault();
var url = $( this ).children( 'a' ).attr( 'href' );
var elem = $( this );
var parent = $( this ).parent().parent();
var html = parent.html(); alert( html );
$.ajax({
type: 'get',
url: url,
data: '',
cache: false,
dataType: 'text',
beforeSend: function( rs ) {
parent.html( '<div class="basket-item item-border" style="width:896px;text-align:center;"><p class="para"><img src="/media/images/spinner.gif" />Please wait...</p></div>' );
},
success: function( rs ) {
parent.html( html );
if( rs = 'YES' ) {
alert( 'Okay' );
} else {
alert( 'Something went wrong' );
}
},
error: function( rs, err ) {
if( rs.status == 0 ) {
alert( '--- Offline' );
} else if( rs.status == 404 ) {
alert( '404 Not Found' );
} else if( rs.status == 501 ) {
alert( '501 Internal Error' );
} else if( err == 'timeout' ) {
alert( '--- Timeout' );
} else {
alert( '--- Unknown' );
}
}
});
});
});
And here is a section of the HTML the JQuery works on
<div>
<div class="basket-item item-border" style="width:512px;text-align:left;">
<p class="para">
<img
width="48"
height="48"
alt="Sample Soap Pack (£3.99)"
src="http://www.mj.local/media/images/products/generic/0929005236213037.jpg" />
Sample Soap Pack</p>
</div>
<div class="basket-item item-border"><p>3.99</p></div>
<div class="basket-item item-border" style="width:256px;text-align:center;">
<p class="button"><a href="http://www.mj.local/shop/add/sample-soap-pack/">
<span class="add">Add to Basket</span>
</a></p>
</div>
</div>
The contents of the parent DIV are replaced with a "Please wait.." message and then restored, as expected so would this alter any way JQuery works? I have another JQuery working okay when swapping HTML so why now with this?
Thanks.
it's because on success you are replacing the html of the parent, your .button will be replaced, and the new .button won't have the click event binded anymore.
You could fix it by using live jQuery <1.7:
$(function() {
$('.button').live('click', function() {
//your function here
});
});
or on for jquery >1.7:
$(function() {
$(document).on("click", ".button", function(){ });
});
You are replacing your .button element inside the callback function for the AJAX request that clicking on the .button element makes and when you remove the .button element the click event handler for that element is also removed. I would use event delegation so the event handler will affect all the elements currently in the DOM and ones added later (for example by an AJAX call):
Just change:
$( '.button' ).click(function( e ) {
To:
$(document).delegate('.button', 'click', function( e ) {
Here are docs for .delegate(): http://api.jquery.com/delegate

Categories