I'm collecting data from a form and sending to a controller
$('form').submit(function(e){
e.preventDefault();
var supplier = $('select[name="supplier"]').val();
var reqdate = $('input[name="reqdate"]').val();
var priority = $('input[name="priority"]:checked').val();
if( supplier !='' && reqdate !=''){
var Material_ID = [];
var Material_Name = [];
var Mat_Quantity =[];
var Unit_Price =[];
var Cost =[];
$('.matid').each(function(){
Material_ID.push($(this).text());
});
$('.matname').each(function(){
Material_Name.push($(this).text());
});
$('.unitprice').each(function(){
Unit_Price.push($(this).text());
});
$('.matqty').each(function(){
Mat_Quantity.push($(this).text());
});
$('.matcost').each(function(){
Cost.push($(this).text());
});
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('purchase.sessionstore') }}",
method:"POST",
data:{supplier:supplier,reqdate:reqdate,priority:priority,Material_ID:Material_ID,Material_Name:Material_Name,Unit_Price:Unit_Price,Mat_Quantity:Mat_Quantity,Cost:Cost,_token:_token},
success:function(data){
alert(data);
}
});
}
in the controller, I'm trying to put all variables into a Session
public function storeSessionData(Request $request){
if($request){
$supplier = $request->get('supplier');
$duedate = $request->get('reqdate');
$priority = $request->get('priority');
$token = $request->get('_token');
$materialid = $request->get('Material_ID');
$materialname = $request->get('Material_Name');
$matqty = $request->get('Mat_Quantity');
$unitprice = $request->get('Unit_Price');
$cost = $request->get('Cost');
$cart[] = array($supplier, $duedate,$materialid,$priority,$materialname,$matqty,$unitprice,$cost);
Session::set('cart', $cart);
return $cart;
}
}
I want to open a view with session data to show ordered items (just like a page to confirm cart)
What I want to do - collect data from a dynamic form and display them with a second view, on that view I will save them to database
how can I do it, please explain
Related
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 ?
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);
}
}
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.
Hi I am able to retrieve data from a specific table using codeigniter ajax but i don't see everything.
It's simply a chat system I implemented allowing users to send messages to one another.
Everytime a new record is inserted, the latest record does not show up but the previous ones do.
Please see my code attached with this.
Thank you.
Controller - Chats.php
public function ajax_get_chat_messages()
{
echo $this->_get_chat_messages();
}
public function _get_chat_messages()
{
$recipient = $this->input->post('recipient');
$chat = $this->Chats_model->get_chat_messages($recipient);
if($chat->num_rows() > 0)
{
$c_html = '<ul>';
foreach($chat->result() as $cht)
{
$c_html .= '<li>'.$cht->username.'</li>';
$c_html .= '<p>'.$cht->chat_message_content.'</p><hr><br>';
}
$c_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $c_html);
return json_encode($result);
}
}
JS - Chat2.js
$(document).ready(function () {
setInterval(function () { get_chat_messages();}, 2500)
function get_chat_messages()
{
$.post(base_url + "user/chats/ajax_get_chat_messages", {recipient: recipient}, function (data) {
if (data.status == 'ok')
{
$("div#view").html(data.content);
} else
{
//there was an error do something
}
}, "json");
}
/*function get_chat_messages() {
$.ajax({
type: "POST",
dataType: 'json',
url: base_url +"user/chats/ajax_get_chat_messages",
data: {recipient: recipient}, // pass it as POST parameter
success: function(data){
$("div#view").html(data);
console.log(data);
}
});
} */
get_chat_messages();
});
model - Chats_model.php
public function get_chat_messages($recipient)
{
$session = $this->session->userdata('user_id');
$query = "SELECT * FROM chat_messages cm JOIN users u on u.user_id = cm.user_id where cm.user_id = $session and cm.recipient = $recipient or cm.user_id = $recipient and cm.recipient = $session ORDER BY cm.chat_message_id ASC ";
$result = $this->db->query($query, array($recipient));
return $result;
}
Image also attached
I get an error "500 Internal Server Error" when I retrieve a lot of data. When I choose a country having only 10 cities it works, but when I choose a country with 100 thousands cities the error occurs. Any solution for this?
My Script
$('#country_id').on('change',function(e){
console.log(e);
var cat_id = e.target.value;
var e = document.getElementById("country_id");
var str = e.options[e.selectedIndex].value;
document.getElementById('txt').value = str;
$.get('/public/countrycity/ajax-sub?cat_id=' + cat_id, function(data){
$('#state').empty();
$.each(data, function(category, subcatObj){
$('#state').append('<option value="'+subcatObj.id+'">'+subcatObj.FULL_NAME_ND+'</option>');
});
});
});
$('#state').on('change',function(e){
console.log(e);
var e = document.getElementById("state");
var strs = e.options[e.selectedIndex].value;
document.getElementById('txts').value = strs;
});
My Controller
public function getCountry()
{
$countries = Country::all();
$cat_id = Input::get('cat_id');
$cities = City::where('id', '=', $cat_id)->get();
return View::make('countrycity.countrycity')
->with('countries',$countries)
->with('cities',$cities)
->with('title', 'Ajax');
}
public function getCity()
{
$cat_id = Input::get('cat_id');
$cities = City::where('CC_FIPS', '=', $cat_id)->get();
return Response::json($cities);
}