Codeigniter Auto complete Multiple fields not working Properly - php

I want to use jQuery auto complete multiple Fields in codeigniter framework I referred this tutorial.But my search filed not working.text fields doesn't show auto complete list
here is my code please help me to solve this.
view
.....................
<div class="row">
<form action="" name="students" method="post" id="students">
<input type="text" name="patientId" id="patientId_1" class="ui-autocomplete-input">
<input type="text" name="firstname" id="firstname_1" class="ui-autocomplete-input">
<input type="text" name="nic" id="nic_1" class="ui-autocomplete-input">
<input type="text" name="telephone" id="telephone_1" class="ui-autocomplete-input">
</form>
</div>
jQuery
.......
$('#patientId_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'http://localhost/cafdc/BillingController/test',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patient_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#firstname_1').val(names[1]);
$('#nic_1').val(names[2]);
$('#telephone_1').val(names[3]);
}
});
controller
.......................
public function test()
{
$data=$this->Billing_Model->get_data();
echo json_encode($data);
}
model
....................
public function get_data()
{
if($_POST['type'] == 'patient_table'){
$row_num = $_POST['row_num'];
$result =$this->db->query( "SELECT patientId, fname, nic, tpnumber FROM tblpatient where name LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['patientId'].'|'.$row['fname'].'|'.$row['nic'].'|'.$row['tpnumber'].'|'.$row_num;
array_push($data, $name);
}
}
}

Your code is not working Because you are not return any data from model
public function get_data()
{
if($_POST['type'] == 'patient_table'){
$row_num = $_POST['row_num'];
$result =$this->db->query( "SELECT patientId, fname, nic, tpnumber FROM tblpatient where name LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['patientId'].'|'.$row['fname'].'|'.$row['nic'].'|'.$row['tpnumber'].'|'.$row_num;
array_push($data, $name);
}
return $data;// return your data
}
}

You have to set type:"POST" in ajax call otherwise it will take it as GET so add the type in your $.ajax call like,
$.ajax({
url:'...',
type:"POST",// add this line in your ajax call
....
})

Related

jquery select2: error in getting data from php-mysql

I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.

After selecting value from autocomplete suggestions, fill in the rest of the fields based on the selected value

So i have a autocomplete in one of my views, that is working, now i want to add a feature where users searches for product writtes in some key words finds it and selects it, when the name of the product is selected i want to dynamically fill in price for that product, the info is in the database, how can I achieve this?
My JQuery for autocomplete
$(function(){
var controller_path = document.getElementById("get_controller_path").value;
$("#product").autocomplete({
source: controller_path
});
});
My view where i want dynamically the price to popup when autocomplete suggestion is selected:
<td><input type="text" id="product" name="prodname"></td>
<input type="hidden" id="get_controller_path" value="<?echo base_url().'admin_site_offers_ctrl/get_product';?>">
<td><input style="width: 60px" type="text" name="price" id="price"></td>
Controller for autocomplete
public function get_product(){
$this->load->model('offers_for_clients_model');
if (isset($_GET['term'])){
$q = strtolower($_GET['term']);
$this->offers_for_clients_model->get_product($q);
}
}
Model for that autocomplete functionality:
function get_product($q){
$this->db->select('*');
$this->db->like('nosauk_lv', $q);
$query = $this->db->get('produkti');
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$row_set[] = htmlspecialchars_decode(stripslashes($row['nosauk_lv'])); //build an array
}
echo json_encode($row_set); //format the array into json data
}
}
How should i approach this? Any pointers to right direction would be amazing! Thanks!
P.S The autocomplete is wokring no worries about that.
You can try like this
$("#product").autocomplete({
source: function( request, response ) {
$.ajax({
url: customurl,
data: {term: request.term},
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
// you can set the label value
return {
label: item.value,
value: item.value,
}
}
}));
}
});
},
select: function( event, ui )
{
// Here again you can call ajax function to get the product price
var prodname=$('#prodname').val(ui.prodid);
getproductprice(prodname);
},
change: function( event, ui )
{
var prodname=$('#prodname').val(ui.prodid);
getproductprice(prodname);
}
});
Please make sure in your model get the id of product also in $row_set[].
In html declare like this
<input type="hidden" name="prodname" id="prodname"> // Here you will get product name id after select the productname
In getproductprice function you can call the ajax function to get the price
function getproductprice(prodname)
{
if(prodname>0)
{
$.ajax({
url:customurl,
data: "prodid="+prodname,
dataType: "json",
success: function( data ) {
$('#price').val(data['price']); // whatever your varaible
}
});
}
}
I think this will help to solve your problem. Thanks
Sorry for late reply this worked for me ended up doing this:
$(function(){
var controller_path = document.getElementById("get_controller_path").value;
$("#product").autocomplete({
source: controller_path, // ceļš uz kontrolieri kur atrodas metode, admin_site_offers_ctrl
select: function(a,b){
$(this).val(b.item.value); //grabed the selected value
getProductsOtherInfo(b.item.value);//passed that selected value
}
});
});
Other function made request to database based on the selected values name
and loaded them in the appropriate fields that i needed, like this:
function getProductsOtherInfo(name){
var site_url = document.getElementById('get_products_other_info').value;
/*alert(site_url);*/
$.post(site_url, {
name : name,
site_url : site_url
},
function(rawdata){
var myObject = JSON.parse(rawdata);
$('#cena_pirms_atl').val(myObject[0].cena_ls);
$('#iepcena').html(myObject[0].ped_ien_ls);
$('#nom_id').val(myObject[0].ID);
getPZtotals();
});
}
The controller:
function get_products_other_info(){
$this->load->model('offers_for_clients_model');
$name = trim($_POST['name']);
$data['products_other_info'] = $this->offers_for_clients_model->get_products_other_info($name);
echo json_encode($data['products_other_info']);
}
The model:
function get_products_other_info($name){
$decode_name = htmlspecialchars(stripslashes($name));
$query = $this->db->where('nosauk_lv', $decode_name)->get('produkti')->result();
return $query;
}
View:
<input type="hidden" name="nom_id" id="nom_id">
<td><input style="width: 60px" type="text" name="cena_pirms_atl" id="cena_pirms_atl"></td>
<td id="iepirkcens"><span id="iepcena"></span></td>

How to pass data to controller to view using json in php?

I using codeigniter.I need to pass data to my controller to view somehow.I manage to pass view to controller(in view when drop-down selected value pass to controller using ajax)
this is my HTML code
<div class="form-group">
<label for="lastname" class="control-label">Your Packages</label>
<?php if(isset($tourbuddy_packages)){?>
<select id="itemType_id" class="form-control input-sm" name="tripbuddy_PackageTitle" onChange="disp_text()">
<?php
foreach ($tourbuddy_packages as $packages) {?>
<option value="<?php echo $packages['PackageID'] ?>"><?php echo $packages['PackageTitle']?></option>
<?php } ?>
</select>
<input type="hidden" name="PackageID" id="country_hidden">
<?php } else { ?>
<select class="form-control input-sm" name="tripbuddy_PackageTitle">
<option>Add Packages</option>
</select>
<?php } ?>
</div>
when drop-down selected a vale i pass data to controller by using ajax and java Script
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
Selected vale pass to tea method in controller
public function tea()
{
$this->session->set_userdata(array('tripbuddy_PackageID'=>$_POST['id']));
$package_data = $this->ci->package_model->get_package($_POST['id']);
$package_cat = $this->ci->package_model->get_package_categories();
$data = array();
$data['tourbuddy_selected_package'] = $package_data[0];
$data['tourbuddy_selected_package_cat'] = $package_cat;
//echo $data['package']['AlbumID'];
$data['tourbuddy_selected_photos'] = $this->photo->get_package_photo_stream($data['tourbuddy_selected_package']['AlbumID']);
//echo var_dump($data['photos']);
echo json_encode($data);
}
now I need to pass $data array to my view without refreshing view page how can i do this ? need a quick help
First you need to add the correct header to your tea() function as it will be returning json
public function tea()
{
header('Content-Type: application/json');
//...
}
Then you will need to add the dataType parameter to your ajax call
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
dataType: 'json', //Added this
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
In your success function you will then be able to access the data like
success: function(response) {
response.tourbuddy_selected_photos.data
}
Controller
class Feature extends CI_Controller
{
public function tea()
{
$post = $this->input->post(); //do some form validation here
$model = Model::get($post); // do all business logic in the model
if(!$model){
//return a Response header rather than a 404View
return $this->output->set_status_header(404);
}
$responce = array(
'something' => $model->something
);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($responce))
->set_status_header(200);
}
}
Untested Javascript
var URL = <?php echo site_url(); ?>// Global URL variable
(function($){
var Form = {
init : function(){
this.Form = $("form#formId"),
this.ItemType = this.Form.find("#itemtype_id");
this.ItemType.on('change', $.proxy(this.change, this));
},
/**
* -----------------------------------------------------------------
* Bind the ItemTypeId change event to this function using $.proxy
* Ajax return's a deffered(promise) so capture it, and do stuff
* -----------------------------------------------------------------
**/
change : function(event){
this.doAjax(event.target).then(
function( data ) // success
{
$(this).html('Success'); // $(this) -> context
},
function( reason ) //fail
{
switch(reason.code)
{
case 404:
default:
$(this).html('no results found');
break;
}
}
);
},
/**
* -----------------------------------------------------------------
* Make the ajax request a wait for it to return a promise
* -----------------------------------------------------------------
**/
doAjax : function( target ){
var data = {
id : target.id
}
return $.ajax({
cache: false,
url : URL + 'feature/tea/',
context : target,
method: "POST",
data : data,
dataType : 'json',
}).promise();
}
}
Form.init();
}(jQuery));

Not able to get inputs in controller or model for an ajax call submit form

I have an ajax call for a form submit; it works fine if I pass my sql arguments when I hard code them, however if I want to pass my sql query arguments with inputs (from View) in my model it says: Message: Undefined index: startDate and endDate.
Here is my View:
<?PHP
$formData2 = array(
'class' => 'form-horizontal',
'id' => 'frm2',
);
echo form_open('gallery/fetchAssociates', $formData2);
?>
<input id="startDate" class="span2" size="16" type="text" />
<input id="endDate" class="span2" size="16" type="text" />
<input type="submit" class="btn btn-primary"
value="Submit" id="querystartEnd" name="querystartEnd" />
<?PHP
echo form_close();
?>
and my javascript for AJAX call is as following:
$.ajax({
type: "POST",
async: false,
dataType: "json",
?>",
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success: function(data) {
html = "<table id='myTable'><thead><tr id='test'><th>ID</th><th>Start Date</th><th> LName</th></tr></thead><tbody id='contentTable'>";
for (var i = 0; i < data.length; i++)
{
html = html + "<tr id='trResponses' ><td><div >" + data[i]['id']
+ " </div></td><td><div >" + data[i]['start'] +
"</div> </td><td><div >" + data[i]['username'] +
"</div></td></tr>";
}
html = html + "</tbody></table>";
$("#resultFrm2").html(html);
},
error: function()
{
alert('error');
}
});
and here is my controller:
public function fetchAssociates() {
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
//die();
$this->load->model('user_model');
echo json_encode($this->user_model->getAll());
}
and my Model method is as following:
public function getAll()
{
$wtc = $this->load->database('wtc', TRUE);
$sql = "SELECT username, MIN(timeIn) as start
FROM tc_timecard
GROUP BY userid having MIN(timeIn) > ? and MIN(timeIN) < ?
order by MiN(timeIN);";
//$q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
$q = $wtc->query($sql, array($this->input->post('startDate'),
$this->input->post('endDate')));
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
As you see my comments in my code: if I have
//echo($_POST["startDate"]);
//echo($_POST["endDate"]);
uncommented in firebug in response it says "Message: Undefined index: startDate and endDate."
Also in my controller if I have
// $q = $wtc->query($sql, array('2013-01-08', '2013-01-23'));
un-commented it works but once I want to pass the inputs by the following line of code it does not work :
$q = $wtc->query($sql, array($this->input->post('startDate'), $this->input->post('endDate')));
What can be the reason that I cannot access my inputs in my controller or Model?
If it is not clear for you, please let me know which part you need more clarification.
EDITED:
It is worth mentioning that my ajax call is inside the following block:
$('#frm2').submit(function(e)
{
e.preventDefault();
//My AJAX call here
});
Many thanks in advance,
You are not passing any data through ajax
// Collect data from form which will be passed to controller
var data = {
start_data : $('#startDate').val(),
start_data : $('#endDate').val(),
}
$.ajax({
type: "POST",
async: false,
dataType: "json",
data : data // data here
url: "<?php echo base_url('gallery/fetchAssociates') ?>",
success : function(data){
// Success code here
},
error: function(data){
// error code here
}
})

How to return a php variable in ajax callback and use it?

I am send a ajax request to php file where i will update the database and and i will select a value according to my condition. But how to return that $variable in ajax callback and show it in input text box.
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
}
});
my PHP file is
<?php
$conn = mysql_connect('localhost', 'root', 'root') or die("error connecting1...");
mysql_select_db("cubitoindemo",$conn) or die("error connecting database...");
if($_GET['id']==2) //taking
{
$book_id = $_GET['bookid'];
$startdate = $_GET['startdate'];
$update_validity = "UPDATE booking SET valid = '2',start_date_timestamp = '$startdate' where book_id = '$book_id'";
$query = mysql_query($update_validity);
if($query==TRUE)
{
$get_select_query = "select start_date_timestamp from booking where book_id = '$book_id'";
$get_query = mysql_query($get_select_query);
$row = mysql_fetch_assoc(get_query);
$startdate_return = $row['start_date_timestamp'];
echo $startdate_return;
}
}
?>
You should use json format like:
in your php file
$arrFromDb = array(
'id' => 1,
'bookName' => 'Da Vinci Code'
)
echo json_encode( $arrFromDb ); exit();
in you script
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
var book = $.parseJSON(data) // now book is a javascript object
var bookName = book.bookName;
}
});
I hope this will help you
Create an element in your page like <span> and give it a unique ID like <span id="testspan"></span>. This is where the text gets displayed. Then in your JS;
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
$( "#testspan" ).html(result);
}
});
Just echo in your php file, the output (instead of being shown by the browser as a default PHP page) will be usable in the JS as the result of the ajax call (data)
Try to use val(),
HTML
<input type="text" id="inputId" />
Js
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(data) {
$( "#inputId" ).val(data);
}
});
PHP CODE
<?php
echo $bookid= isset($_REQUEST['bookid']) ? $_REQUEST['bookid'] : "No bookid";
// you can use $_GET for get method and $_POST for post method of ajax call
return
?>
In updatenewuser.php
//after all operations
echo $variable_to_pass;
Then in the ajax request :
$.ajax({
url:'updatenewuser.php',
data: {
bookid: bookid,
id: 2,
startdate: cal
}, // pass data
success:function(result) {
alert(result);//result will be the value of variable returned.
$("#input_box").val(result); //jquery
document.getElementById("input_box").value = result; // Javascript way
}
});
HTML being :
<input type="text" id="input_box" value=""/>
Cheers

Categories