How to check the 'id' values in the controller? - codeigniter

my javascript code values that will print the data from ajax response
<script type="text/javascript">
function getval(get) {
var id = get.value;
// alert(id);
$.ajax({
type : "POST",
url :"http://localhost/codeIgniter/index.php/admin/ajax",
data :{id:id},
success:function(data){
$('#sub_category').html(data);
//window.location = "<?php echo site_url('admin/examdetails/form'); ?>"
}
});
}
</script>
Controller Function: that will handle ajax request
function ajax()
{
$id = $_POST['id'];
echo "<script>";
echo "alert(id);";
echo "</script>";
$this->load->model('admin_model');
$query = $this->admin_model->get_sub_details($id);
echo '<select name="sub_category" id="sub_category">';
foreach($query->result_array as $row)
{
$name = $row['name'];
$id = $row['id'];
echo '<option value="'.$id.'">'$name'</option>';
}
echo '</select>';
}

Related

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

Retrieve data using Ajax Php laravel 5.3

According to my scenario when I select a doctor whose id is #slmc, I want to retrieve data relevant to the doctor I have chosen..
This is my blade File -> Admin/channel.blade
<label id="lslmc" for="slmc" class="control-label">Choose a Doctor </label><br />
<select class="form-control" id="slmc" name="slmc" onchange=" getPatient()" >
<option value="">----Select the Doctor----</option>
#foreach($Doctors as $Doctor)
<option value ="{{$Doctor-> slmc}}">{{$Doctor->fname}} {{$Doctor->sname}} </option>
#endforeach
</select>
</div>
<div id ="dd"></div>
Then this is my getPatient() function in the controller
public function getPatient($slmc){
$patients = DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
This is the Ajax call in the script function.
function getPatient() {
var patient = $("#slmc").val();
$.ajax(
{
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'patients': patient},
success: function (data) {
$('#dd').html("");
$('#dd').html(data);
}
}
);
}
This is web.php
Route::get('/Admin/channel/getPatient{slmc}', 'channelController#getPatient' );
Is there something wrong with my Ajax call. I'm new to it.
Route :
Route::get('/Admin/channel/getPatient', 'channelController#getPatient' );
Controller :
ChannelController.php :
use Illuminate\Http\Request;
class ChannelController extends Controller
{
public function getPatient(Request $request){
$patients = \DB::table('channel')->where('slmc', $request->patients)->get();
return $patients;
}
}
I was able to do it
The ajax function goes like this
function getPatient() {
var patient = $("#slmc").val();
$.ajax({
type: 'get',
url: ('/Admin/channel/getPatient'),
data: {'slmc': patient},
success: function (data) {
$('#dd').html("");
var divHtml = "";
divHtml += "<table class='table table-bordered table-hover'>";
divHtml += "<tr>";
divHtml += "<td>" + data[0].pname + "</td>";
divHtml += "<td>" + data[0].address + "</td>";
divHtml += "</tr>";
divHtml += "</table>";
$('#dd').html(divHtml);
console.info(data);
},
error: function (data) {
console.error(data);
}
});
}
And my controller function is
public function getPatient(Request $request) {
$slmc = $request->get('slmc');
$patients = \DB::table('channel')->where('slmc', $slmc)->get();
return $patients;
}
web.php
Route::get('/Admin/channel/{slmc}', 'channelController#getPatient' );

yii2: call controller action in sortable jquery with ajax

I am using jquery sortable plugin to drag and drop items and setting their order. But I am unable to get the response from Ajax. I want to call the controller action from the js so that when I drag the item and drop it, then a response should come. The drag and drop functionality is working fine.
I tried this:
My View:
<div class="status-index info">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<ul class="sortable_status">
<?php
$items = StatusType::find()->orderBy('order')->all();
//var_dump($items);exit;
//$content = array();
foreach ($items as $item) {
echo '<li class="text-items"><label for="item'.$item->order.'"><span class="items-number">'.$item->order.'</span></label>
<label id="item'.$item->order.'" />'.$item->title.'</label>
<br/>
</li>';
}
?>
</ul>
</div>
JS:
$(function () {
var LI_POSITION = 'li_position';
$("ul.sortable_status").sortable({
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('.sortable_status li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
/*handle : '.handle',
update : function () {
var order = $('.sortable_status').sortable('serialize');
$(".info").load("process-sortable.php?"+order);
} */
});
});
Controller:
public function actionSortable()
{
/* foreach ($_GET['text-items'] as $position => $item)
{
$sql[] = "UPDATE `status_type` SET `order` = $position WHERE `id` = $item";
}*/
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
empty
';
}
}
why don't use an ajax call on stop ?
$("ul.sortable_status").sortable({
stop: function(event, ui) {
$.ajax({
type: "POST",
url: myUrl
data: {my-data: "any-value"}
})
.success(function(data) {
//your logic here
})
.fail(function() {
//your logic here
});
}
});
I used to define in my layout on the head tag of my html my variables as following
<head>
<script>
var myUrl = "<?php echo Url::to(['controller/action']); ?>";
</script>
</head>

Resources