Jquery Codeigniter - Autocomplete not working - javascript

I am facing a problem with autocomplete in codeigniter. When inserting some text on input, it shows a dropdown but no value in there. Looks like this: Screenshot
Viewing error on console : Screenshoot
Here is my code :
Model
var $unit_table = "sales_unit";
public function getUnit($searchTerm)
{
$this->db->like('nopol', $searchTerm, 'both');
$this->db->order_by('nopol', 'ASC');
$this->db->limit(10);
return $this->db->get($this->unit_table)->result();
}
Controller
function jsonUnitAutocomplete()
{
if (isset($_GET['term'])) {
$result = $this->m_admin->getUnit($_GET['term']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}
View
<input type="text" class="form-control" name="npl" id="drop-npl"><br>
<input type="text" class="form-control" name="tyunit"><br>
<input type="text" class="form-control" name="kg"><br>
<input type="text" class="form-control" name="seat"><br>
<script>
$(document).ready(function() {
$("#drop-npl").autocomplete({
source: "<?php echo site_url('control_admin/jsonUnitAutocomplete') ?>",
select: function(event, ui) {
$('[name="npl"]').val(ui.item.nopol);
$('[name="tyunit"]').val(ui.item.type);
$('[name="kg"]').val(ui.item.kategori);
$('[name="seat"]').val(ui.item.seat);
}
});
});
</script>

Isn't you just read incorrect query param name? and in the Controller you not declare else statement for your if-else, so the result will be undefined
From what I noticed, I assumed No.Polisi is input text with the name "npl". So you can change 'term' on your controller into 'npl', like below:
function jsonUnitAutocomplete()
{
if (isset($_GET['npl'])) {
$result = $this->m_admin->getUnit($_GET['npl']);
if (count($result) > 0) {
foreach ($result as $row)
$data[] = array(
'nopol' => $row->nopol,
'type' => $row->type,
'kategori' => $row->kategori,
'seat' => $row->seat
);
echo json_encode($data);
}
}
}

Related

Dynamic drop down using single table in codeIgniter

Table
Here when I select Category 1 from drop down I should get district names which comes under Category 1 and for Category 2 I should get districts of Category 2 and so on....
As of now in my code i'm pulling out all district names from my district table master by using district codes. But I should get district names based on category selection.
View:
<select class="form-control" name="category" id='cat_id'>
<?php
foreach($query1 as $row)
{
echo '<option value="'.$row->category.'">'.$row->category.'</option>';
}
?>
</select>
<select name="placename" id="placename">
<?php
foreach($query2 as $row)
{
echo '<option value="'.$row->district_name.'">'.$row-
>district_name.'</option>';
}
?>
</select>
Model:
function viewcatplace()
{
$this->db->select("district.district_name");
$this->db->from('district');
$this->db->join('jc_place_master', 'district.district_code =
jc_place_master.district');
$query = $this->db->get();
return $query->result();
}
Controller:
public function viewcatplace()
{
$this->load->model('JcMeetingExpense_model');
$data['query1'] = $this->JcMeetingExpense_model->viewcatprice();
$data['query2'] = $this->JcMeetingExpense_model->viewcatplace();
$this->load->view('JcMeetingExpense/place_view',$data);
}
You can use this demo for your solution : https://www.codexworld.com/dynamic-dependent-dropdown-codeigniter-jquery-ajax/
It can be only done by ajax:
In controller:
public function index()
{
$web = array();
$web['title'] = 'Select tool';
$web['content'] = 'web/category_index';
// $web['data'] = $this->Common_model->get_all('category','*','','');
$web['data'] = $this->db->query('SELECT DISTINCT category FROM category')->result();
$this->load->view('web_template', $web);
}
Load the category data in select option:
<select class="form-control" id="select_category">
<option value="" disabled selected>Select category</option>
<?php if (isset($data) && !empty($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<option value="<?php echo $value->category; ?>"><?php echo $value->category; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
<select class="form-control" id="append_district"></select>
Using jquery change event get the data using ajax call:
<script type="text/javascript">
$(document).on('change',"#select_category",function (e) {
var optVal= $("#select_category option:selected").val();
if (optVal) {
$.ajax({
type: "post",
url: "getCategoryDetails",
cache: false,
data: {'category' : optVal},
success: function(json){
try {
var obj = jQuery.parseJSON(json);
$('#append_district').empty();
var append_data = '';
if (obj.length > 0) {
$.each(obj, function( index, value ) {
append_data += '<option value="'+value.district+'">'+value.district+'</option>'
});
$('#append_district').append(append_data);
}
} catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
The data can be get by JSON format.In controller add this method:
public function getCategoryDetails() {
$category = $_POST['category'];
$categoryData = $this->db->query('SELECT district FROM category where category="'.$category.'"')->result();
echo json_encode ($categoryData) ;
}

Fetching data using onChange jquery ajax issue

here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post

Cakephp 3.0 autocomplete jquery ui

I need to know why the following isnt working .This code will extract data from index controller to search get json data.Neither does any request is made and nothing happens
I'm new to both Cakephp 3.0
I'm trying to get an autocomplete / autosuggest working in CakePHP 3.0 but everything I find is either for 1.3 or not for Cake at all and I don't know what to do to get it working properly.I precisely need it for cakephp 3.0
snippet
1.CarsController.php
This is carscontroller accesses when an ajax request and will encode in json data
2.CarsTable.php
fetches data from the carstable
3.index.ctp
is the view page and autocomplete method
<?php
namespace App\Controller;
use App\Controller\AppController;
class CarsController extends AppController {
public function index() {
$this->loadComponent('RequestHandler');
if ($this->request->is('ajax')) {
$term = $this->request->query('term');
$carNames = $this->Car->getCarNames($term);
$this->set(compact('carNames'));
$this->set('_serialize', 'carNames');
}
}
}
?>
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class Carstable extends AppModel {
public function getCarNames ($term = null) {
if(!empty($term)) {
$cars = $this->find('list', array(
'conditions' => array(
'name LIKE' => trim($term) . '%'
)
));
return $cars;
}
return false;
}
}
?>
<?php
//let's load jquery libs from google
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', array('inline' => false));
$this->Html->script('https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', array('inline' => false));
//load file for this view to work on 'autocomplete' field
//form with autocomplete class field
echo $this->Form->create();
echo $this->Form->input('name', array('class' => 'ui-autocomplete',
'id' => 'autocomplete'));
echo $this->Form->end();
?>
<script type="text/javascript">
(function($) {
$('#autocomplete').autocomplete({
source: "<?php (array('controller'=>'Cars','action'=>'search')); ?>",
datatype:"json",
minLength: 1
})
})
</script>
This code snippet will work for autocomplete in cakephp 3.0
View for search \Template\post\
Search.ctp
<?php
use Cake\Routing\Router;
use Cake\View\Helper\UrlHelper;
?><div class="ui-widget">
<?php
echo $this->Form->create('Posts', array('action' => 'search'));
echo $this->Form->input('name',array('id' => 'Autocomplete'));
echo $this->Form->end();
?></div><div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript">
$(document).ready(function($){
$('#Autocomplete').autocomplete({
source:'<?php echo Router::url(array("controller" => "posts", "action" => "search")); ?>',
minLength: 1
}); });
</script>
In your controller add this function .Change database and other variable properly.
src\Controller\PostController.php
public function search()
{
if ($this->request->is('ajax')) {
$this->autoRender = false;
$name = $this->request->query('term');
$results = $this->Posts->find('all', array(
'conditions' => array('Posts.title LIKE ' => '%' . $name . '%')
));
$resultArr = array();
foreach($results as $result) {
$resultArr[] = array('label' =>$result['title'] , 'value' => $result['title'] );
}
echo json_encode($resultArr);
}}
In routes.php add this line
Router::extensions('json', 'xml');

Require that the input is in the datalist

I have an form input of type datalist, in this list is about 5000 options, because of the large amount of options a select form just is not practical as you are allowed to type and it suggests what you want with a datalist.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2><label class='control-label' style="font-size: 20px;">Product code</label></h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
This is what i have now, however the user can type and submit things that are not in the list and i can not allow this. How can i stop this from happening?
Alert the user if the field has a incorect value
$('input[type="submit"]').on('click',function(e) {
$datalistval= $('#ItemSelect').val();
if ($('option[value="'+$datalistval+'"]').length == 0) //if no option is found alert the user
{
alert('incorect datalist value');
e.preventDefault();
}
});
jsfiddle: https://jsfiddle.net/ev63ghwk/
If you're willing to use jQuery UI's autocomplete this would work:
<?php // tweak the below to use your data
$arr = array( array('Name' => 'one'), array('Name' => 'two'), array('Name' => 'three') );
$optsArr = array();
foreach ($arr as $a) {
array_push( $optsArr , '"'.htmlentities( $a["Name"] ).'"' ); ;
}
$options = implode(",", $optsArr)
?>
var availableTags = [<?php echo $options ?>];
$(function() {
$( "#ItemSelect" ).autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// ui.item property is null if the input was not found in the list
$("#ItemSelect").val("");
}
}
});
});
Here's a working Demo

how to create an autocomplete textbox in wordpress?

Hi i am developing a plugin in wordpress.
i tried code for create autocomplete text box in my customized form.
Ajax Calling function
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
foreach($result as $dis)
{
$data.=$dis->city."<br>";
}
echo $data;
die();
}
add_action( 'wp_ajax_city_action', 'city_action_callback' );
add_action( 'wp_ajax_nopriv_city_action', 'city_action_callback' );
Shortcode function
function my_search_form() {
?>
<script>
jQuery(document).ready(function($) {
jQuery('#city').keyup(function() {
cid=jQuery(this).attr('val');
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
//alert(response);
});
});
});
</script>
<input type="text" id="city" name="city" autocomplete="off"/>
<?php
}
this code return related results perfectly in variable response.
But i don't know how create a text box look like a autocomplete box.
Please explain me how to do that in wordpress?
Just add a div under the input tag
HTML Code:
<input type="text" id="city" name="city" autocomplete="off"/>
<div id="key"></div>
replace the div after the success on you ajax.
Ajax Code:
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
$('#key').html(response);
});
PHP Code:
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
echo '<ul>'
foreach($result as $dis)
{
echo '<li>'.$dis->city.'</li>';
}
echo '</ul>'
die();
}

Categories