Request data of AJAX POST is null in Laravel Controller - php

I'm trying to send via AJAX data, I'm doing a post and then receiving it on the laravel controller.
I'm getting an error that the data is null.
I tried multiples ways to fix it but I'm not able to figure out how to do it.
Ajax:
$(document).ready(function () {
$('table tbody').sortable({
update: function (event, ui) {
$(this).children().each(function (index) {
if ($(this).attr('data-position') != (index + 1)) {
$(this).attr('data-position', (index + 1)).addClass('updated');
}
});
saveNewPositions();
}
});
});
function saveNewPositions() {
var positions = [];
$('.updated').each(function () {
positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
$(this).removeClass('updated');
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(positions);
$.ajax({
url: 'cursos',
method: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(positions),
contentType: "application/json; charset=utf-8",
traditional: true,
})
}
Laravel Controller:
public static function updateOrder(Request $request)
{
foreach ($request->positions as $position) {
$index = $position[0];
$newPosition = $position[1];
$seccion = SectionCourse::findOrFail($index);
$seccion->order = $newPosition;
$seccion->save();
}
return response('success', 200);
}
Doing a dd of the request, I receive this:

I fixed it using $request->toArray() instead of $request->positions directly

Related

Laravel 6 - Ajax - retreiving file - Internal error 500

I'm trying to fetch file via ajax from the laravel storage (I don't want to use the public folder as the docs should be only available for the admins). So the Ajax function calls a Route (post) , which calls the controller function to respond, but getting 500 internal server error in the console all the time.
If I dd() the request, or some string right in the begining of the controller function I get that back as output. so the request actually happens with the proper data. CSRF tokens are included.
The route:
Route::post('/tes/admin/filter/docview/', 'AdminTravelExpenseController#showdoc')-
>name('admin.tes.displayDoc');
The controller:
public function __construct()
{
$this->middleware('auth');
//adminvalidator here
}
public function showdoc(Request $request){
$item = \App\TravelExpense::find($request['id']);
if($request['src'] == 1){
$url = $item->doc_url1 ;
}
else{
$url = $item->doc_url2 ;
}
if (!Storage::disk('local')->exists($filePath)){
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return \Response::json($response);
}
And the ajax:
$('.docview').on('click',function(){
var id = $(this).data('id');
var src = $(this).data('src');
var form_data = new FormData();
form_data.append('id', id);
form_data.append('src', src);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/tes/admin/filter/docview/',
type: "POST",
processData: false,
contentType: false,
data: form_data,
success: function(data){
console.log(data);
$('.docDisplay').html(data);
}
});
});
Not sure what I'm missing here.
Thanks for the help in advance!

Get date from datepicker using Ajax with Laravel controller

i want to get the datepicker value when user selected a date and send that using ajax to a laravel controller. this code is not worked for me..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#date').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date, instance) {
$.ajax({
type: "POST",
url: '/process_date',
data: date,
success: function(result)
{
console.log(result);
}
});
}
});
here is my route,
Route::post('/process_date', 'TimeController#ajaxTime');
here is my controller,
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
Try changing your code to this because I have been reading the documentation and testing it with some code of my own and this is what I came up with
$('#date').datepicker({
format: 'dd-mm-yyyy',
}).on('changeDate', function(e) {
$.ajax({
type: "POST",
url: '/process_date',
data: {
date: e.date.toString(),
},
success: function(result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
})
and also change your TimeController class from
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
to
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
return $request->all(); // This will get all the request data.
}
}
to receive better results in your browser console.

Upate table with AJAX in Laravel 5.3 not working

I trying to use an AJAX PUT request to update a row in my database and I am trying to send the request to my controller. This is my AJAX call:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leased').val();
var truckModel = $('#truck-model').val();
$.ajax({
url: 'editTruck',
type: 'put',
data: {
truckNo: truckNo,
truckOwner: truckOwner,
vehicle_number: vehicle_number,
capacity: capacity,
end_of_insurance: end_of_insurance,
end_of_kteo: end_of_kteo,
truckCode: truckCode,
leased: leased,
truckModel: truckModel
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(){
console.log('success');
},
error: function(){
console.log('something went wrong');
}
});
});
So far so good. If I console.log() my data is seems I can get them from the form. I am using Laravel Collective for the form:
{!!Form::open(array('action' => ['Trucks#editTruck'], 'method' => 'put')) !!}
and my route is the following:
Route::put('/editTruck', 'Trucks#editTruck',function(){ });
Now I am using Request $request in the parameters of the controller but somehow it looks like I cannot get the incoming values. For example the following var_dump will say NULL.
public function editTruck(Request $request)
{
$data = $request->input('truckNo');
var_dump($data);
}
Same happens if I use
$data = $request->truckNo;
instead. So I am wondering how can I get the values that are been sent to my controller with my AJAX call? Why am I getting NULL values?
What I was planning to do is:
public function editTruck(Request $request)
{
$singleTruck = Truck::find($request->truckNo);
$singleTruck->truckNo = $request->input('truckNo');
$singleTruck->truckOwner = $request->input('truckOwner');
........
$singleTruck->save();
}
You can find the answer here:
https://laravel.io/forum/02-13-2014-i-can-not-get-inputs-from-a-putpatch-request
You should change your form method and method inside your js code to "post", and add extra field "_method" = "PUT"
probably it can help.
OK I found it. Looks like the AJAX was malformed. So here is how it should be written:
$('#edit-trucks').on('click',function(){
var truckNo = $('#XA').val();
var truckOwner = $('#truck-owner').val();
var vehicle_number = $('#vehicle-number').val();
var capacity = $('#vehicle_capacity').val();
var end_of_insurance = $('#end-of-insurance').val();
var end_of_kteo = $('#end-of-KTEO').val();
var truckCode = $('#truck-code').val();
var leased = $('#leasing').val();
var truckModel = $('#truck-model').val();
var outGoingData = {
'truckNo': truckNo,
'truckOwner': truckOwner,
'vehicle_number': vehicle_number,
'capacity': capacity,
'end_of_insurance': end_of_insurance,
'end_of_kteo': end_of_kteo,
'truckCode': truckCode,
'leased': leased,
'truckModel': truckModel,
};
var data = JSON.stringify(outGoingData);
$.ajax({
url: 'editTruck',
type: 'POST',
data: data, <!-- The error was here. It was data: {data}-->
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: 'application/json',
dataType: 'JSON',
success: function(response){
alert("The data should be "+ response);
},
error: function(){
console.log('skata');
}
});
});

JSON responce populating undefine in dropdown

JSON response is not populating in dropdown perhap query gat the result perfectly.
alert the success function i.e
alert(result.data);--[object object]
here is my html code
Jquery
function fillTransferJobPositionAreaDropDown( job_type_id,province_id,region_id,district_id,tehsil_id,uc_id, area_id) {
var loadDDUrl = baseApiUrl + "Employee/all_new_job_positions_area/"+job_type_id+"/"+province_id+"/"+region_id+"/"+district_id+"/"+tehsil_id+"/"+uc_id+"/"+area_id;
console.log(loadDDUrl);
debugger;
newJobPositionIDFld.empty();
newJobPositionIDFld.append($("<option />").val("0").text("Select New Job Position"));
newJobPositionIDFld.select2('val', '0');
var url = loadDDUrl;
$.ajax({
url: url,
accepts: 'application/json',
cache: false,
type : 'GET',
dataType: 'jsonp',
success: function (result) {
alert(result.data);
console.log(result.data);
// Handle the complete event
if(result.data == null) return;
$.each(result.data, function () {
newJobPositionIDFld.append($("<option />").val(this.job_position_id).text(this.job_position_id+'-'+this.job_name));
});
}
});
}//End Ajax call
PHP
$this->db->select('jp.job_position_id,jp.jobposition_title as job_name');
$this->db->from('job_positions jp');
$this->db->where('jp.job_type_id', $job_type_id);
$this->db->where('jp.province_id', $province_id);
$this->db->where('jp.region_id', $region_id);
$this->db->where('jp.district_id', $district_id);
$this->db->where('jp.tehsil_id', $tehsil_id);
$this->db->where('jp.uc_id', $uc_id);
$this->db->where('jp.area_id', $area_id);
$this->db->get()->row_array();
Your query returns a object, not an array of objects, so remove the loop:
success: function (result) {
newJobPositionIDFld.append($("<option/>").val(result.data.job_position_id).text(result.data.job_position_id+'-'+result.data.job_name));
}

Ajax data isn't being received by php

Hello overflowers!
I can't seem to manage to send my ajax data over to my php page correctly, it has worked perfectly fine before but now it is not working.
I'm getting the correct data via console.log but on my php page i'm getting Undefined index error.
Jquery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$("#new-task").on('submit', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {task_takers_pre : task_takers_pre },
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_submit'])){
$task_takers = $_POST['task_takers_pre'][0];
var_dump($task_takers);
}
EDIT
jQuery
var task_takers_pre = [];
var task_takers = [];
var i = 1;
$(".new-task-takers ul.select_takers li").on('click', function(){
$(this).each(function(){
$(this).toggleClass("active");
if($(this).find('.fa').length > 0){
$(this).find('.fa').remove();
i -= 1;
var removeItem = $(this).data("id");
task_takers_pre.remove(removeItem);
console.log(task_takers_pre);
}else{
$('<i class="fa fa-check" aria-hidden="true"></i>').insertBefore($(this).find("div"));
i += 1;
task_takers_pre[i] = $(this).data("id");
console.log(task_takers_pre);
}
$.each(task_takers_pre, function (index, value) {
if ($.inArray(value, task_takers) == -1) {
task_takers.push(index, value);
}
});
});
});
$(".assign").on('click', function(){
console.log(task_takers_pre);
$.ajax({
type: 'POST',
url: './core/includes/new_task.php',
cache: false,
data: {task_takers_pre : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
$.ajax({
type: 'POST',
url: '',
cache: false,
data: {'task_takers_pre' : task_takers_pre},
success: function(data) {
//console.log(data)
}
});
});
PHP
if(isset($_POST['task_takers_pre'][0])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
}
if(isset($_POST['task_takers_pre'])){
$task_takers2 = $_POST['task_takers_pre']; // Just for testing
var_dump($task_takers2); // Just for testing
}
What you are attempting to do is use the same PHP code to handle the Button Press from the Form AND the AJAX Call. Don't!
(note: This answer is Only based upon the code that has been provided and what is trying to achieved with this code.)
So your current PHP is, which I am guessing is what you call when you click the submit button... In that case $_POST['task_takers_pre'] will not exist as you are generating that from the JS and sending it in the AJAX Call.
Write a separate AJAX Call.
You need to create a separate file to handle your AJAX calls and have it perform what duties it needs to perform.
// This is just for testing my AJAX Call
public function ajax_post(){
if(isset($_POST['task_takers_pre'])){
$task_takers = $_POST['task_takers_pre'][0]; // Just for testing
var_dump($task_takers); // Just for testing
die();
}
else {
// Illegal access/entry do something...
echo 'Error - I had better check what I am posting.';
die();
}
}
If you juse want to send some data in the AJAX Call when you click the submit button,you could return false to prevent form submission in the submit event.
$("#new-task").on("submit", function(){
$.ajax({
type: "POST",
url: "",
cache: false,
data: {task_submit:1, task_takers_pre: task_takers_pre},
success: function(data){
console.log(data);
}
});
return false;
});

Categories