How to change 'active/inactive status of user' through ajax? - 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.

Related

Laravel 5.8 after first ajax request success run another one in same button

i want to store invoice head row in one table and after that store its items rows in another table so i want to run two ajax requests first one for invoice head and the second is for invoice items
here is my ajax code :
function functionOne() {
var allVals = [];
$.each($(".record__select:checked"), function () {
allVals.push($(this).val());
});
var amount = $('#amount').val();
var client = $('#client').val();
var mobile = $('#mobile').val();
var pnr = $('#pnr').val();
var branch = $('#branch').val();
var join_selected_values = allVals.join(",");
alert(allVals.length);
if(amount!="" && client!="" && mobile!="" && pnr!="" && branch!="" && allVals.length >=1) {
$.ajax({
url: "/deposits_service",
type: "POST",
data: {
_token: $("#csrf").val(),
amount: amount,
client: client,
mobile: mobile,
pnr: pnr,
branch: branch
},
cache: false,
success: function (data) {
if(data['success']){
$.ajax({
url: "/deposits_service/",
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".record__select:checked").each(function() {
$(this).parents("tr").remove();
});
// alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
// alert('Whoops Something went wrong!!');
// alert(data.responseText);
alert(data['error']);
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
}
else
{
alert("Please select row and make sure that you fill all the field !");
}
}
and here is Controller code :
public function store(Request $request)
{
if(Input::get('payment_type') == 'cash'){
$this->validate($request,[
'amount'=>'required|integer|min:0',
'client'=>'required',
'mobile'=>'required',
'pnr'=>'required',
'branch'=>'required',
]);
$deposit = new Deposit();
$deposit->paymentType = $request->get('payment_type');
$deposit->amount = $request->get('amount');
$deposit->total_fare = $request->get('fare');
$deposit->total_tax = $request->get('tax');
$deposit->total_vat = $request->get('vat');
$deposit->amountRemain = $request->get('amount');
$deposit->amount_arabic = $request->input('amount_arabic');
$deposit->amount_english = $request->input('amount_english');
$deposit->client = $request->get('client');
$deposit->mobile = $request->get('mobile');
$deposit->direction = $request->get('directing');
$deposit->pnr = $request->get('pnr');
$deposit->paymentStatus = "0";
$deposit->rowStatus = "0";
$deposit->used = "0";
$deposit->transferred = "0";
$deposit->userSign = Auth::user()->shortsign;
$deposit->branch = $request->get('branch');
$deposit->cashierSign = null;
$deposit->date = Carbon::now();
$deposit->save();
session()->flash('success',__('site.added_successfully'));
return redirect()->route('deposits.index');
}
else {
$this->validate($request,[
'amount'=>'required',
'client'=>'required',
'mobile'=>'required',
'pnr'=>'required',
'branch'=>'required',
]);
$deposit = new Deposit();
$deposit->paymentType = $request->get('payment_type');
$deposit->amount = $request->get('amount');
$deposit->amountRemain = $request->get('amount');
$deposit->amount_arabic = $request->input('amount_arabic');
$deposit->amount_english = $request->input('amount_english');
$deposit->client = $request->get('client');
$deposit->mobile = $request->get('mobile');
$deposit->direction = $request->get('directing');
$deposit->pnr = $request->get('pnr');
$deposit->paymentStatus = "0";
$deposit->rowStatus = "0";
$deposit->used = "0";
$deposit->transferred = "0";
$deposit->userSign = Auth::user()->shortsign;
$deposit->branch = $request->get('branch');
$deposit->cashierSign = null;
$deposit->date = Carbon::now();
$deposit->save();
session()->flash('success',__('site.added_successfully'));
return redirect()->route('deposits.index');
}
}
public function updateAll(Request $request)
{
$depositId = Deposit::latest()->first()?: app(Deposit::class);
$newID = (int)$depositId->id ;
$ids = $request->ids;
DB::table("presales")->whereIn('id', explode(",",$ids))->update(['deposit_refund_no'=>$newID+1,'status'=>'Closed']);
return response()->json(['success'=>"Products Updated successfully."]);
}
here is routes :
Route::post('/deposits_service', [Deposit::class, 'store']);
Route::delete('/deposits_service', [Deposit::class, 'updateAll']);
the problem now is that the first request run ok but the second not running
would you please help me with this ?

Request input null in Laravel Controller

Hi I have a problem with getting the value of input using request in Controller, it's always return null. This is my code in jquery I am using Ajax to pass value to controller.
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance', '')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
And this is my code in controller. I am trying to get the data using request but it returns null when I checked it. What would be the cause? Please help me. Thanks
public function index($id = 0,Request $request)
{
if($id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$id)->get();
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$id)-
>get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances','sUser'));
// dd($start);
}
// return view('manage.index');
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
}
don't forget {{csrf_field }} in form and put id in input name is id
$('.generate').click(function(){
var dstart = $("#datepickerstart").val();
var dend = $("#datepickerend").val();
//var empid = $('#empid').val();
if($('#empid').val().length == 0)
{
empid = 0;
}
else{
empid = $('#empid').val();
}
var dStart = 0;
var dEnd = 0;
//alert(empid);
$.ajax({
type: "GET",
url: "{{route('manageattendance.update')}}"+"/"+empid,
data:$('#attendanceform').serialize(),
success: function(response)
{
console.log(response);
// alert("data caught");
$('.content').load('manageattendance/'+empid);
},
error: function(error)
{
console.log(error);
//alert("not caught ");
// alert($('#editForm').serialize());
}
});
//alert(dstart);
//alert(dend);
});
public function index(Request $request)
{
if(request->id == 0){
$current_date = date('Y-m-d');
$attendances = Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')-
>where('Date','=',$current_date)->get();
//$start = '2021-02-10';
//$end = '2021-02-11';
//$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->whereBetween('Date',
[$start,$end])->get();
return view('manage.index',compact('attendances'));
}
else
{
$start = $request->input('datepickerstart');
$end = $request->input('datepickerend');
$newS = date('Y-m-d', strtotime($start));
$newE = date('Y-m-d', strtotime($end));
$sUser = User::select('name')->where('id','=',$request->id)->get();
$attendances =
Attendance::select('Name','CheckIn','CheckOut','Note','Date','TotalHours')->where('user_id','=',$request->id)->whereBetween('Date',
[$start,$end])-
>get();
return view('manage.index',compact(['attendances'=>$attendances,'sUser'=>$sUser]));
// dd($start);
}
}

how to get the value of textarea from innerhtml in javascript and insert into the database using the controller in laravel....?

javascript
$(document).on('click', '#sidebar-user-box', function() {
var userID = $(this).attr("class");
var username = $(this).children().text() ;
if ($.inArray(userID, arr) != -1)
{
arr.splice($.inArray(userID, arr), 1);
}
arr.unshift(userID);
chatPopup = '<div class="msg_box" style="right:270px" rel="'+ userID+'">'+
'<div class="msg_head">'+username +
'<div class="close">x</div> </div>'+
'<div class="msg_wrap"><div class="msg_body" id="msg_body" ><div class="msg_push"></div></div>'+
'<div class="msg_footer"><textarea class="msg_input" id="msg_input" rows="4" style="resize:none;"></textarea></div></div></div>' ;
$("body").append( chatPopup );
displayChatBox();
});
$(document).on('keypress', 'textarea' , function(e) {
if (e.keyCode == 13 ) {
var msg = $(this).val();
$(this).val('');
if(msg.trim().length != 0){
var chatbox = $(this).parents().parents().parents().attr("rel") ;
$('<div class="msg-right">'+msg+'</div>').insertBefore('[rel="'+chatbox+'"] .msg_push');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);
var url= " /sendchatmessage ";
$.ajax({
headers:{'X-CSRF-token':$('meta[name=csrf-token]').attr('content')},
async:true,
type:"post",
contentType:false,
url:url,
data:msg,
processData:false,
success:function(){
console.log("success");
}
});
}
} // revision
});
controller
public function send_chat_message(Request $req){
$name = $req->input('msg_input'); //
$newchat = new ChatMessage;
$newchat->frsender_userId = Auth::user()->user_id;
$newchat->frchat_msg = $name;
$newchat->save();
}
web.php
Route::post('/sendchatmessage', 'MessengerController#send_chat_message')->name('sent-chat');

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

JQuery Ajax POST 500 Interval error

I have an error 500 (Internal Server Error), I dont know what is the problem
m.ajaxTransport.a.send # jquery.min.js:4
(anonymous function) # add:198
fichier javascript:
$("#addItem").on('click',function(e){
e.preventDefault();
var id_produit = parseInt($("#produit_id option:selected").val());
var prix = parseFloat($('#prix_produit').val());
var remise = parseFloat($('#remise_produit').val());
var qte = parseInt($('#count_produit').val());
var id_facture = <?php echo($count_id); ?>;
var data = [];
data = {
FacturesProduit: {
facture_id : id_facture,
produit_id : id_produit,
prix : prix,
remise : remise,
quatite : qte
}
};
console.log(data);
var url = <?php echo $this->Html->url(array('controller' => 'facturesproduits' , 'action' => 'ajout_produit')); ?>;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
console.log(result);
}
});
});
Action :
public function ajout_produit() {
$message = 'error';
if ($this->request->is('ajax')) {
$data = $this->request->data;
if ($this->FacturesProduit->save($data)) {
$message = 'success';
}
}
echo json_encode($message);
die();
}
thanks

Resources