Request input null in Laravel Controller - ajax

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);
}
}

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 ?

codeigniter foreach not displaying all records in table

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

Modify request object in Symfony 2

i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!

How to set the maximum execution time using ajax (get)

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);
}

Check customer email is already exist in magento using ajax prototype

I want to check customer email is already exist or not using ajax prototype. I tried lots of things but it is not working. I write my code like this.
<script type="text/javascript">
//<![CDATA[
var dataForm = new VarienForm('form-validate', true);
Validation.add('validate-emaila', 'Email already exist', function(v) {
var url = '/customer/account/checkEmail/email?email=' + encodeURIComponent(v);
var ok = false;
new Ajax.Request(url, {
method: 'get',
asynchronous: false,
onSuccess: function(transport) {
alert(transport.responseText);
var obj = response = eval('(' + transport.responseText + ')');
validateTrueEmailMsg = obj.status_desc;
if (obj.ok === false) {
Validation.get('validate-email').error = validateTrueEmailMsg;
ok = false;
} else {
ok = true; /* return true or false */
}
},
onFailure: function(){ alert('something wrong') },
onComplete: function() {
if ($('advice-validate-email-email')) {
$('advice-validate-email-email').remove();
}
if ($('advice-validate-email-email_address')) {
$('advice-validate-email-email_address').remove();
}
if ($('advice-validate-email-billing:email')) {
$('advice-validate-email-billing:email').remove();
}
if ($('advice-validate-email-shipping:email')) {
$('advice-validate-email-shipping:email').remove();
}
if ($('advice-validate-email-_accountemail')) {
$('advice-validate-email-_accountemail').remove();
}
}
});
return ok;
});
//]]>
</script>
I called a function In customer/accountcontroller
public function checkEmailAction()
{
$bool = 0;
$email = $this->getRequest()->getParam('email');
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail($email);
if ($customer->getId()) {
$bool = 1;
}
$jsonStatus = 200;
$info = array( "status" => $bool);
$this->getResponse()->setBody(json_encode($info))->setHttpResponseCode($jsonStatus)->setHeader('Content-type', 'application/json', true);
return $this;
}
I am getting wrong response from php function. it is returning full page html. instead of 0 or 1.
I have tried lots of thing but giving same response. Can any one tell me what is wrong in this?
it is wrong code for checking customer.You need to add website id to customer load
First need to change customer check url move from customer accountcontroller.php to checkout onepagecontroller.php. Because magento cannot easly add to accountcontroller.php
url ='<?php echo $this->getUrl('checkout/onepage/checkEmail', array('_secure'=>true)); ?>'
var request = new Ajax.Request(
url,
{
method:'get',
parameters: {email:encodeURIComponent(v)}
onSuccess: function(transport)
{
if(transport.status == 200)
{
var data = transport.responseText.evalJSON();
if(data.success==true){
}
}
}
}
);
In checkout onepagecontroller.phpadd the below code
public function forcecheckAction()
{
$response=array();
$email = $this->getRequest()->getParam('email');
try{
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email); //load customer by email i 
/* if customer has ,then login */
if($customer->getId()>0){
$response['success'] = true;
}else{
$response['success'] = false;
}
}catch(Exception $e)
{
$response['success'] = false;
$response['message'] = $e->getMessage();
}
$this->getResponse()->setBody(Zend_Json::encode($response));
}

Resources