500 (Internal Server Error) in Laravel - php

Please help. I have this jQuery code
$('.modal-footer').on('click', '.edit', function() {
var serializedData = $(".form-horizontal").serialize();
var criscore = new Array();
$('input[name^=criscore]').each(function(){
criscore.push({score:$(this).val(), criid:$(this).data('criid')});
});
for (var key in criscore) {
var score = criscore[key].score;
var criid = criscore[key].criid;
//console.log(score +" s "+ criid);
$.ajax({
method: 'post',
url: '/judges/candidates/scorecandidates',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {
'_token': $('input[name=_token]').val(),
'canId': $('input[name=canId]').val(),
'catId': $('input[name=catId]').val(),
'criId': criid,
'score': score,
'judgeId': $('input[name=judgeId]').val()
},
success: function(data) {
console.log(data);
}
});
}
});
and in my controller is
public function scorecandidates(Request $req)
{
$data = new Score();
$data->canId = $req->canId;
$data->catId = $req->catId;
$data->criId = $req->criId;
$data->score = $req->score;
$data->judgeId = $req->judgeId;
$data->save();
return response()->json($data);
}
my problem is that it is still keeps having an 500 (Internal Server Error)
Even though I already put the csrf token is different ways.. Can any body help me?
Thank you

Related

Request data of AJAX POST is null in Laravel Controller

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

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

Jquery ajax wrong data response

It looks like that i got wrong type or something going on
function updateCart()
{
var dataArray= [];
var i=0;
var item;
$('.cd-cart .wrapper .body .product').each(function()
{
var item=new Array();
i++;
var $element = $(this)
qty=parseInt($element.find('select').val());
name=$element.find('h3 a').html();
price=parseInt($element.find('.price1').text().replace('₽',''));
id=parseInt($element.attr('id').replace('product_',''));
image=$element.find('img')[0].src;
item['id']=id;
item['price']=price;
item['name']=name;
item['qty']=qty;
item['image']=image;
dataArray.push(item);
});
var jObject={};
jObject = JSON.stringify(dataArray);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/updateCart',
type: 'get',
dataType:'json',
data: ({dataArray:jObject}),
success:function(data){
console.log(data);
},
error:function(error){
console.log(error);
}
});
}
Server-side got return $_GET;
I got this response from the server :Object {dataArray: "[[],[]]"}
What can i do to get Normal response?
P.S dataArray is an array of an array
I did some reformatting here while I was trying to run down your codes flow. Generally if you need an associative array style grouping in JavaScript you want to use an object, not an array. Arrays are indexed, Objects keyed. In my example I used a constructor function to build your item. You could also let data = {}; and then build the keys like data.id = 1.
// formatted for readability.
function updateCart() {
const data = buildCart();
let dataObj = JSON.stringify(data)
makeRequest('/updateCart', dataObj);
}
function buildCart() {
let data = [];
$('.cd-cart .wrapper .body .product').each(function() {
const $element = $(this);
let qty = parseInt($element.find('select').val())
, name = $element.find('h3 a').html()
, price = parseInt($element.find('.price1').text().replace('₽',''))
, id = parseInt($element.attr('id').replace('product_',''))
, image = $element.find('img')[0].src;
data.push(new Item(id, price, name, qty, image));
});
return data;
}
function Item(id, price, name, qty, image)
{
this.id = id
this.price = price;
this.name = name;
this.qty = qty;
this.image = image;
}
function makeRequest(url, dataObj)
{
let token = $('meta[name="csrf-token"]').attr('content');
let jqXHR = $.ajax({
url: url,
type: 'GET',
headers: 'X-CSRF-TOKEN': token,
dataType: 'json',
jsonp: false,
data: {dataArray: dataObj}
});
jqXHR.done(function(data, status, jqXHR) {
// success
});
jqXHR.fail(function(jqXHR, status, error) {
// failure
});
}

Laravel 5.3 - jquery ajax (internal server error 500)

I am trying to use jquery ajax in laravel5. What actually happens all the time is consolelog giving me an internal server error 500. I found some csrf solutions and added them to my code but they didnt help me. Any ideas?
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
$.ajax({
type : "POST",
url : "/save_like",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: {photoId : photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
I also added this meta to my head:
<meta name="csrf_token" content="{{ csrf_token() }}" />
Everything goes through routes:
`Route::any('/save_like', 'Controller#saveLike');`
To the controller:
public function saveLike($photoId){
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
}
First the _token should be always sent in the http request so you could just add it to the data :
$('.takImg').click(function(){
var photoId = $(this).parent().attr('id');
var _token = $('meta[name="csrf_token"]').attr('content');
$.ajax({
type: "POST",
url: "/save_like",
data: {_token:_token, photoId:photoId},
success : function(msg) {
console.log(msg);
},
complete : function(r) {
console.log(r);
},
error: function(error) {
console.log(error);
}
});
});
internal server error 500 mean the problem come from your server what mean in your case here it come from the action saveLike in your controller, so my guess is that this problem come from the expression WHEREid= ? :
DB::update('UPDATE `photo_links` SET likes = likes + 1 WHERE `id` = ?', array($photoId));
____________________________________________________________^^^^^^^^^^
You're passing an array to = and that will cause the issue, try :
public function saveLike(){
$photoId = INPUT::get('photoId');
DB::update("UPDATE `photo_links` SET likes=likes+1 WHERE `id` = $photoId");
}
Hope this helps.
That's what i use in my app:
$("#captcha-gen-button").click(function(e){
e.preventDefault();
$.ajax({
url: "/captcha-ajax",
method: "POST",
headers: { 'X-CSRF-Token' : '{!! csrf_token() !!}' }
}).done(function(image) {
$("#captcha-img-container").html(image);
});
});
I think the problem is here:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
What happened when there is no token? beforeSend won't return anything. Change to this:
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
return xhr;
},

submit form to a php file with angular

i would like to submit my form to a php file
var myApp = angular.module('myApp',[]);
myApp.controller('FormController', function($scope, $http) {
$scope.task = {
group: 'fix',
showme: true,
select1: 'basique',
select2: 'micro',
select3: '1',
select4: '1',
select5: 'jour'
};
var server = 'http://localhost/myserver.php?cd=add';
var parameters;
$scope.submit = function(form) {
angular.forEach($scope.task, function(value, key) {
if(value) {
if(key === 'date') {
value = new Date(value).getTime();
}
parameters += '&'+key+'='+value;
}
});
console.log(server+parameters);
//$http.post(server+parameters)
//.success(function(result) {
// console.log("success", result);
//})
//.catch(function(error) {
// console.log("error", error);
//})
}
})
this is the codpen codepen
is this valid?
the result at should be http://localhost/myserver.php?cd=add'name='&'describe='
You are create query string using foreach() and pass with server url but. you are use $http.post(). you have to use $http.get() if you want pass with server url.
Below example with help
$scope.submitForm = function($valid)
{
myobject = {'email' : $scope.user.email, 'pass' : $scope.user.pass};
Object.toparams = function ObjecttoParams(obj)
{
var p =[];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: WSURL + '/login',
method: "POST",
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config)
{
}
}).error(function (data, status, headers, config)
{
});
}

Categories