Laravel 500 (Internal Server Error) on Ajax Post - php

I've tried doing my research on my issue but have not been able to solve it. I'm attempting to Ajax POST on click. I've read the most popular issue is due to the csrf_token, but I believe I have that handled properly?
I keep getting this error:
POST http://example.com/refreshCalendar 500 (Internal Server Error)
Here is my code...
My meta tag for the csrf token at the top of my master.blade.php file
<meta name="token" content="{{ csrf_token() }}">
Route:
Route::post('/refreshCalendar', ['as' => 'refreshCalendar', 'uses' =>'Calendar#refreshCalendar']);
Js function
function refreshCalendar(obj){
var month = obj.data('month');
var year = obj.data('year');
history.pushState(null, null, '/month/'+month+'/year/'+year);
var data = {
"month":month,
"year":year,
_token:$('meta[name="csrf-token"]').attr('content')
};
$.ajax({
type: "POST",
url: '/refreshCalendar',
dataType: 'html',
async:true,
data: data,
success: function(data){
$('#calendarHolder').html(data);
},
error: function(){alert("There was an error retrieving information");return false;}
});
}
My Controller:
namespace App\Http\Controllers;
use DateTime;
use Illuminate\Http\Request;
class Calendar extends Controller
{
public function refreshCalendar(Request $request)
{
//Set data to $request
$data = $request->all();
return show($data['month'], $data['year'], true);
}
}

<meta name="token" content="{{ csrf_token() }}">
_token:$('meta[name="csrf-token"]').attr('content')
Your meta tag name is token, however you are looking for the meta tag named csrf-token.

If meta is present, you should look to your network for issues.
That was the culprit for me:

Related

Laravel undefined variable into blade after calling from JSON

I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade
I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
#foreach(json_decode($seller, true) as $row)
<a href="{{route('Report', $row->id) }}" >
{{ __('Show Report of ')}} {{$row->car_title}}
</a>
#endforeach
Controller
$seller = Sellers::take(1)->latest()->get();
return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);
JavaScript
$("#submit-all").click(function(e){
e.preventDefault();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "post",
url: "{{ route('form_for_private_sellers') }}",
data : $('#msform').serialize() + "&_token=" + _token,
dataType: 'JSON',
beforeSend: function(){
// Show loading image
$("#se-pre-con").show();
},
success: function(data) {
window.location = "http://127.0.0.1:8000/report/";
},
complete:function(data){
// Hide loading image
$("#se-pre-con").hide();
}
});
});
As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";
will hit the route
Route::get('/report', function () {
return view('report');
})->name('private_seller_report');
Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
$sellers = Seller::get(); //your logic
return view('report', ['seller' => $sellers]);
})->name('private_seller_report');
Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.
you need two route for this
first for rendering blade
return view('report');
and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller

Laravel 5 App - AJAX Post Request not accepting the token and throwing a 500 internal server error

So, I've been looking on here for the better part of 3 hours as to why my code isn't working. I don't think my ajax request is detecting my CSRF token even though i've tried multiple ways to implement it. New to AJAX requests so go easy.
Goal:
Submit an ajax POST request to /email/subscribe/ and add the email address provided by the user to the email_subscribers table.
I've tried adding the following to my code to get the token to show up:
The meta tag and the Ajax Setup.
Top of the file
<meta name="csrf-token" content="{{ csrf_token() }}">
In the script tag INSIDE the jquery $(document).ready() function
// CSRF Ajax Token
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Hidden input field
I've also added a hidden input field and tried to insert the token inside the data object inside the ajax post.
HTML
<input type="hidden" id="token" value="{{ csrf_token() }}">
Javascript tag
var token = $('#token').val();
// var token = $('meta[name="csrf-token"]').attr('content'); //Tried this way
$.ajax({
type: 'POST',
url: '/email/subscribe/',
dataType: 'json',
data: {
email: email,
'_token': token,
// "_token": "{{ csrf_token() }}", //Tried this way as well
"_method": 'POST',
},
success: function (data) {
// Check Server Side validation
if($.isEmptyObject(data.errors)){
console.log(data['success']);
}else{
// Validation Failed Display Error Message
console.log(data.errors);
}
},
error: function (data) {
console.log(data);
}
}); // End Ajax POST function
Here is my web.php file
// Email Routes
Route::prefix('email')->group(function() {
// Create Post Route for subscribing
Route::post('/subscribe', 'EmailSubscriptionsController#subscribe')->name('email.subscribe');
});
and my EmailSubscriptionsController
class EmailSubscriptionsController extends Controller
{
// Store the Email into the database
public function subscribe(Request $request) {
// Validate the request
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
// If the validation fails
if($validator->fails()) {
return response()->json([
'errors' => $validator->errors()->all(),
]);
}
// New Section Object
$subscription = new EmailSubscription;
// Add Name into Section Object
$subscription->email = $request->email;
// Save the Section
$subscription->save();
// Return The Request
return response()->json([
'success' => 'Record has been saved successfully!'
]);
} // End Subscribe
} // End Controller
Whats really weird is the fact that when i submit the request with NOTHING but the following in my subscribe() function inside my controller:
// Return The Request
return response()->json([
'success' => 'Record has been saved successfully!'
]);
It doesn't return an error.... Just passes the success message to the console. I'm not sure what i'm doing wrong as I have this working (an ajax post request) in another portion of my site.
Start by looking in storage/logs/laravel.log for the exception stack trace. That should give a more clear indication of what is failing.
The web inspector also allows you to see the response which usually includes the trace.
A common cause of 500 ISEs is improperly importing classes via use.
Use It Like This:-
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}

Link to a specific part of a page

I have a div that has lots of posts which is created dynamically from the database. The div has input for comment facility as well. I have no problems in posting the comments and I do it using a POST method. Then I redirect to the page using return redirect('/'); method. But it links to the beginning to the page which doesn't create a good impression on the user. The user might be in the middle of the page and when he/she comments he will go to the beginning of the page and will have to scroll down again. Luckily, I have the divs with class equal to the post_id. So, isn't there any method to go to the post in which the user posted using that class?
attach the id with the url like /#post-id
Inside your contorller where you are processing and saving the comments:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
public function yourCommentSaveFunction()
{
...
//Get the Post ID and store in $postid
return Redirect::to(URL::previous() . '#' .$postid);
}
This should work fine.
But the best way would be to use AJAX to post comments.
Edit (As request by OP)
THE AJAX METHOD
Controller will be something like:
public function saveComment(Request $request)
{
//you do the saving part..
...
$comment = $request->comment;
//after saving the comment return a json response
//you can also send other varibales like username, created at etc..
return Response::json(array(
'success' => true,
'comment' => $comment,
));
}
Route:
Route::post('/save-comment', [
'as' => 'save-comment',
'uses' => 'yourController#saveComment',
]);
And your View:
<form action="{{ route('save-comment') }}" class="comment-form">
<input type="text" name="comment">
<input type="submit" name="submit">
<input type="hidden" name="_token" value="{{ csrf_token() }}"
<div class="comment"></div>
</form>
<script>
$('.comment-form').submit(function(event){
event.preventDefault();
var comment = $this.val();
var token = $('.token').val();
var $url = "{{ route('save-comment') }}";
$.ajax({
url: route,
type: 'POST',
data: {_token: token, comment: comment},
dataType: 'JSON',
success: function (data) {
$(".comment").append('<div class="new-comment">' +data.comment +'</div>');
},
error: function(data) {
console.log("Something went wrong");
}
});
});
</script>
Please note: this is just a sample code.

POST 500 (Internal Server Error) Ajax

I want to send post request with ajax to controller in laravel. The ajax request send two input arguments and I want controller to find the column in the database with the first argument and then to set the name attribute with the second input argument. But I have this error message in console 500 (Internal Server Error).
Ajax function:
var $emailInput = $('input[name=eemail]').val();
var $finduser = $('[name=userName]').val();
$.ajax({
type:"POST",
url:'/code/task1/public/editUserAdmin',
data: {
'emailInput' : $emailInput,
'finduser' : $finduser,
},
success:function(data){
// $("#editEmail").attr("readonly", true);
// $("#editEmail").val(data[0].name);
alert("OK");
}
});
Route:
Route::post('/editUserAdmin', 'usersController#editUserAdmin');
Controller function:
$findUserInput = $request->input('finduser');
$user = User::where('name',$findUserInput)->first();
if(!$user){
return response()->json(['status'=>false,'Description' => 'User could not be found.']);
}
//$user->name = $request->input('nameInput');
$user->email = $request->input('emailInput');
$user->save();
}
And also i import csrf everywhere because last time when I was making AJAX call i have problem with this csrf and the following code has fixed my problem, but now is not working.
<meta name="csrf-token" content="{{ csrf_token() }}">
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN' : $('meta[name="csft-token"]').attr('content')
}
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
and this
<h3 class="media-heading" name="userName">{{ $user->name }}</h3>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="text" class="form-control paddingzero" class=text-center" readonly value="Name Name">
<input type="text" class="form-control paddingzero" class=text-center" name="eemail" id="editEmail" readonly value="{{ $user->email }}">
Any idea?
Ajax does not have a "type" property. You will need to pass POST as method
$.ajax({
method: "POST",
url:'/code/task1/public/editUserAdmin',
data: {
'emailInput' : $emailInput,
'finduser' : $finduser,
},
success:function(data){
alert("OK");
}
});
If you are in dev mode you should enable error loggin / output. You can just open dev tools F12 (in chrome for example) and have a look at the error output. Proably it would be method not allowed or whatever.
Another minor thing is that i would recommend to not prefix actual variables with $ if you do not reference the jquery object.
var $emailInput = $('input[name=eemail]').val();
var $finduser = $('[name=userName]').val();
Instead do
var $emailInput = $('input[name=eemail]'); // if you need it more than once
var email = $emailInput.val();
or if you only need it ones better name it
var emailInput = $('input[name=eemail]').val();

laravel 5 simple ajax retrieve record from database

How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
I have this html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
PS: im a newbie in Laravel 5.
At first, add following entry in your <head> section of your Master Layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:
Route::post('employees/{branch_no}', 'EmployeeController#getemployee');
Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller you should send json_encoded data, for example:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
First check url of page from which ajax call initiates
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
In Routes
Route::get('page-using-ajax/datalists', xyzController#abc)
In Controller Method
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
Add in your route:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController#YourMethod'
]);
Ajax:
Change:
url: "employees"
to:
url: "/employees"

Categories