typeahead with bootstrap and codeigniter - codeigniter

i saw a lot of ways to make typeahead, but still can't working with mine. did i make a mistake?
here is my code.
view : personal.php
<script>
$(function() {
$('#search').typeahead({
source: function(typeahead, query) {
$.ajax({
url: "messages/search_name",
type: "post",
data: "search=" + query,
dataType: "json",
async: false,
success: function(data) {
typeahead.process(data);
}
});
}
});
});
</script>
<input type="text" name="search" id="search" class="typeahead">
controller : messages
public function search_name()
{
$data = $this->mysms_model->search_name_person();
echo json_encode($data);
}
model : mysms_model
public function search_name_person()
{
$office = $this->input->post('search');
$this->db->select('name');
$this->db->from('contacts');
$this->db->like('name', $office);
$query = $this->db->get();
$office_array = array();
foreach ($query->result() as $row) {
$office_array[] = $row->name;
}
$data['office'] = $office_array;
return $data;
}
my table name is contacts(cid, name).
thank for helping me.

Related

Yii2, send AJAX request with link

I need to send AJAX request using link.
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
May be construction like this?
<?php
$js = <<<JS
$(".messages_close").click(function () {
var id = 8;
$.ajax({
url: "'.\yii\helpers\Url::toRoute(['messages/exclude','id'=>8]).'",
type: "get",
data: "id="+this.id,
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR :: ' + 'id=' + this.id);
}
});
});
JS;
$this->registerJs($js);
Is it possible? Thank you
UPDATE 1
Thanks for #vvpanchev and #Serghei Leonenco
I did some changes:
added use yii\helpers\Url and changed url:;
removed data: "id="+this.id
removed var id = 8 it used in URL
I still get ERROR alert! ((
How can I get SUCCESS, or better return message from controller?
Here is my code looks like:
view\messages.php
<?php
use yii\helpers\Url;
?>
...
<a href="#" class="messages_close">
<i class="far fa-window-close"></i>
</a>
...
<?php
$js = <<<JS
$(".messages_close").click(function () {
$.ajax({
url: "' . Url::toRoute(['messages/exclude','id'=>8]) . '",
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
MessageController.php (it opens in browser without problem)
<?php
namespace app\controllers;
use Yii;
use app\models\MessagesUsers;
use yii\web\Controller;
class MessagesController extends Controller
{
public function actionExclude($id)
{
return 'Success ID=' . $id;
}
}
Thank you for your help!
SOLUTION
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);
<?php
$url = Url::toRoute(['messages/exclude']);
$js = <<<JS
$(".messages_close").on('click', function () {
$.ajax({
url: "{$url}",
data: {id: 8},
type: "get",
success: function(){
alert('SUCCESS');
},
error: function () {
alert('ERROR');
}
});
});
JS;
$this->registerJs($js);

How can I fetch autocomplete data into their respected element using Ajax and Laravel?

Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});

How to get value of Selected items of Select2 when submitted?

What options I should set to get the value of the options when I submit the form?
I am using Select2. I have given the code I have to setup the select2, controller that returns the data, the html code that renders the element.
Html Code to add the select2 element:
<div class="form-group row"><label class="col-lg-2 col-form-label">Keyword</label>
<div class="col-lg-10">
<select class="form-control w-50" name="keywords[]" id="keyword" multiple="multiple">
</select>
<span class="form-text m-b-none">One or multiple keywords</span>
</div>
</div>
Datasource is an Ajax call:
$(document).ready(function() {
$('#keyword').select2({
tags: true,
tokenSeparators: [',', ' '],
placeholder: 'Select keyword',
ajax: {
url: 'https://rankypro.dev/app/json/keywords',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});
Controller:
public function getKeywords(Request $request){
$search = $request->search;
if($search == ''){
$keywords = Term::orderby('name','asc')
->select('id','name')
->where('taxonomy','keyword')
->limit(5)
->get();
}else{
$keywords = Term::orderby('name','asc')->select('id','name')
->where('taxonomy','keyword')
->where('name', 'like', '%' .$search . '%')
->limit(5)
->get();
}
$results = array();
foreach($keywords as $keyword){
$results[] = array(
"id"=>$keyword->id,
"text"=>$keyword->name
);
}
echo json_encode($results);
exit();
}
I am testing with:
public function store(Request $request)
{
dd($request->keywords);
}
I get the following:
array:2 [
0 => "Tools"
1 => "SEO"
]
I actually need ids of the keywords. Would you please give some hints how can I get that.
I think their is some issue in rendering data. Try to replace
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
With
processResults: function (data) {
return {
results: data.item
};
},
select2 automatically render id and name.

Delete record with out page refresh in codeigniter is not working

Hi all i am trying to delete my record from datatable with out page refresh in codeigniter i have used ajax i don't know where i have done mistake its not deleting the record
Below is the my view:
<tbody>
<?php
if (!empty($employees)) {
foreach ($employees as $emp) {
?>
<tr>
<td><?php echo $emp->emp_name; ?></td>
<td><?php echo $emp->salary; ?></td>
<td class='text-center'>
<button type="submit" class="btn btn-info btn-xs confirmation" name="login"><i class='fas fa-edit'></i></button>
</td>
<td class='text-center'>
<button type="submit" onClick="return ConfirmDelete()" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script>
$(document).ready(function(){
$(".empdelete").click(function(e){
alert();
e.preventDefault();
$.ajax({
alert();
type: "POST",
url: "<?=site_url('Employee/delete');?>",
cache: false,
data: {id:$(this).attr("id")}, // since, you need to delete post of particular id
success: function(data) {
if (data){
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
</script>
Here is the my controller:
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete=$this->Emp_model->delete($id);
if($empdelete){
echo true;
} else {
echo false;
}
}
Here is my model's method delete:
function delete($id)
{
$sql = "DELETE FROM employees WHERE id=?";
return $this->db->query($sql,array($id));
}
Can any one help me how can i do that with out page refresh i want to delete my record.
Thanks in advance.
Try this:
$(document).ready(function () {
function ConfirmDelete() {
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
$(".empdelete").click(function (e) {
var obj = $(this);
e.preventDefault();
//alert(); what's this do?
if (ConfirmDelete() == false) {
return false;
}
$.ajax({
//alert(); this can't go here
type: "POST",
url: "<?php echo site_url('Employee/delete'); ?>",
cache: false,
data: {id: $(this).attr("id")},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
obj.closest('tr').remove();
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
and remove HTML onClick:
<button type="submit" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
Hope this will help you :
Your button should be like this :
<button type="button" onClick="return ConfirmDelete(this)" class="btn btn-danger btn-xs confirmation empdelete" data-id="<?=$emp->id;?>"><i class='fas fa-times'></i></button>
Your ajax code should be like this :
function ConfirmDelete(obj)
{
var x = confirm("Are you sure you want to delete?");
if (x == true)
{
var id = $(obj).data('id');
alert(id);
if (id != '')
{
//do you ajax here
$.ajax({
type: "POST",
url: "<php echo site_url('Employee/delete'); ?>",
cache: false,
data: {'id': id},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
}
}
else
{
return false;
}
}
Your controller should be like this :
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete = $this->Emp_model->delete($id);
if($empdelete)
{
echo true;
} else
{
echo false;
}
exit;
}
Your delete method should be like this :
function delete($id)
{
$this->db->where('id',$id);
$this->db->delete('employees');
return $this->db->affected_rows();
}

I can't update status by use the checked box

Please help i can't update the status by use the checked box.
When i selected the check box and select delete button, status will change to 'deleted' but now i can't update the data.
This is my view
<a href="javascript:;" id="delete" class="myButton" >Delete</a>
<div>
<input type="checkbox" class="cb_invoice" id="<?php echo $r->INVOICENUMBER;?>" value="<?php echo $r->INVOICENUMBER;?>">
</div>
This my script
<script>
$('#delete').click(function() {
var _url = "<?php echo site_url('commission/delete_invoices');?>";
var d_obj = $(".cb_invoice");
var d_val = [];
for (var i = 0; i < d_obj.length; i++){
if(d_obj[i].checked){
d_val.push(d_obj[i].value);
}
}
$.ajax({
url: _url,
data: {data: d_val},
type: 'post',
success: function(data) {
//console.log(data);
location.reload();
}
});
});
</script>
This my controller
function delete_invoices(){
$invoice = $this->input->post('data');
foreach ($invoice as $invoice) {
$this->m_commission->delete_invoice($invoice);
}
}
This is my model
function delete_invoice($invoice){
$this->db->update('salesinvoiceheader');
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
}
Change the order of update as follows in your modal:-
function delete_invoice($invoice){
$this->db->set('STATUS','deleted');
$this->db->where('INVOICENUMBER', $invoice);
$this->db->update('salesinvoiceheader');
}

Resources