Codeigniter Autocomplete search box with JSON, MySql - php

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>

Related

Show product variations on shop pages in woocommerce

I have the same problem which was talked over here
I have added the code using PHP snippets plugin, but I'm not sure where to add the ajax code
I just want to add product variations on shop page with possiblity of adding to cart without reloading the page
you can also check my website over here
if you don't have access to your main script files and you can't add another files then you can add the script to WordPress Footer using wp_footer hook as follow:
add_action('wp_footer', 'myScript');
function myScript()
{
?>
<script>
jQuery(document).ready(function ($) {
"use strict";
$('.custom_add_to_cart').click(function (e) {
e.preventDefault();
var id = $(this).next().next().next().attr('value');
var data = {
product_id: id,
quantity: 1
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response.error) {
alert("Custom Massage ");
$('.custom_add_to_cart').parent().removeClass('loading');
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.custom_add_to_cart').parent().removeClass('loading');
}
});
});
});
</script>
<?php
}
add the whole code under here into your php snippet plugin and it would work like a charm
thanks to #kacholo
/**
* Replace add to cart button in the loop.
*/
function iconic_change_loop_add_to_cart() {
remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
add_action( 'woocommerce_after_shop_loop_item', 'iconic_template_loop_add_to_cart', 10 );
}
add_action( 'init', 'iconic_change_loop_add_to_cart', 10 );
/**
* Use single add to cart button for variable products.
*/
function iconic_template_loop_add_to_cart() {
global $product;
if ( ! $product->is_type( 'variable' ) ) {
woocommerce_template_loop_add_to_cart();
return;
}
remove_action( 'woocommerce_single_variation', 'woocommerce_single_variation_add_to_cart_button', 20 );
add_action( 'woocommerce_single_variation', 'iconic_loop_variation_add_to_cart_button', 20 );
woocommerce_template_single_add_to_cart();
}
/**
* Customise variable add to cart button for loop.
*
* Remove qty selector and simplify.
*/
function iconic_loop_variation_add_to_cart_button()
{
global $product;
?>
<div class="woocommerce-variation-add-to-cart variations_button">
<button type="submit" class="custom_add_to_cart single_add_to_cart_button button"><?php echo esc_html($product->single_add_to_cart_text()); ?></button>
<input type="hidden" name="add-to-cart" value="<?php echo absint($product->get_id()); ?>" />
<input type="hidden" name="product_id" value="<?php echo absint($product->get_id()); ?>" />
<input type="hidden" name="variation_id" class="variation_id" value="0" />
</div>
<?php
}
function iconic_add_to_cart_form_action( $redirect ) {
if ( ! is_archive() ) {
return $redirect;
}
return '';
}
add_filter( 'woocommerce_add_to_cart_form_action', 'iconic_add_to_cart_form_action' );
add_action('wp_footer', 'myScript');
function myScript()
{
?>
<script>
jQuery(document).ready(function ($) {
"use strict";
$('.custom_add_to_cart').click(function (e) {
e.preventDefault();
var id = $(this).next().next().next().attr('value');
var data = {
product_id: id,
quantity: 1
};
$(this).parent().addClass('loading');
$.post(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), data, function (response) {
if (!response) {
return;
}
if (response.error) {
alert("Custom Massage ");
$('.custom_add_to_cart').parent().removeClass('loading');
return;
}
if (response) {
var url = woocommerce_params.wc_ajax_url;
url = url.replace("%%endpoint%%", "get_refreshed_fragments");
$.post(url, function (data, status) {
$(".woocommerce.widget_shopping_cart").html(data.fragments["div.widget_shopping_cart_content"]);
if (data.fragments) {
jQuery.each(data.fragments, function (key, value) {
jQuery(key).replaceWith(value);
});
}
jQuery("body").trigger("wc_fragments_refreshed");
});
$('.custom_add_to_cart').parent().removeClass('loading');
}
});
});
});
</script>
<?php
}

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

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.

Auto complete not showing result jquery

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

php, Jquery autocomplete multiple values, remote!

am new to jquery! I'm using jquery ui autocomplete in my application where the auto complete values comes from database. Here are codes that am using but nothing happens
search.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select name from groups where name like %$q%");
while ($row = mysql_fetch_array($query)) {
echo json_encode($row);
}
?>
Here is test.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> jQuery UI Autocomplete - Multiple, remote </title>
<link rel="stylesheet" href="theme/jquery.ui.all.css">
<script type="text/javascript" src="jquery/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.position.js"></script>
<script type="text/javascript" src="jquery/ui/jquery.ui.autocomplete.js"></script>
<style type="text/css">
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script type="text/javascript">
$(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( "http://localhost/webforum/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="demo">
<div class="ui-widget">
<label for="birds">Birds: </label>
<input id="birds" size="50" />
</div>
</div>
</body>
</html>
Can anyone help me with this?
Thanx in Advance!
How does your json looks like?
in order to work wit jquery-ui autocomplete you need to have at least label and value properties:
{
'label' : 'your_label',
'value' : 'your_value'
}
in your js code you are asking for value property which doesn't seem to bes set on your json produced by php.
here is a similar question: Having problems with jQuery UI Autocomplete
so php has to build the results in the right way:
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$return = array();
$query = mysql_query("select name from groups where name like %$q%");
while ($row = mysql_fetch_array($query))
{
//since we have just 1 value from the db just use it as both value and label
array_push($return,array('label'=>$row['name'],'value'=>$row['name']));
}
echo(json_encode($return));
P.S. it is not that safe make queries with $_GET[] parameters.
Taken from jQuery autocomplete docs.
The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.
When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.
Assuming the above; adjust your code to the following:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("webforum", $conn);
$q = strtolower($_GET["term"]);
$query = mysql_query("select name from groups where name like %$q%");
$results = array();
while ($row = mysql_fetch_array($query)) {
array_push($results, $row);
}
echo json_encode($results);
?>

Categories