Laravel AJAX 500 Internal Server Error, Tokens Match - ajax

When I submit the form, I get this error and the page automatically reloads, but the url in the browser then shows my route and content that I posted in the form. Then, if I go ahead and submit again without reloading the page it works just fine. Could it be that I'm not posting the token itself? I have added the meta tag to the head.
<meta name="csrf-token" content="{{ csrf_token() }}" />
JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#postForm').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
$.ajax({
type: "POST",
url: "/post/"+profileId,
data: {post:body, profile_id:profileId},
success: function(data) {
console.log(data);
}
});
});
Route:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
Controller:
public function postMessage(Request $request, $id)
{
if(Request::ajax())
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
$newMessage = Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
View:
<form role="form" action="#" id="postForm">
<div class="feed-post form-group">
<textarea class="form-control feed-post-input" id="postbody" name="post"></textarea>
<div class="btn-bar">
<button type="submit" class="btn btn-default btn-post"></button>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</form>
UPDATE:
So, the log says that "Request::ajax() should not be called statically" in my controller. I removed that code and it works fine now. However, I want to know if removing it is ok to do of if there's a better way to resolve this. Thanks!
ANSWER: It works by changing
if (Request::ajax()){
// code...
}
to
if ($request->ajax()){
// code...
}

Change Request::ajax() to $request->ajax()

You are doing an AJAX post – you are not supposed to be redirected anywhere at all. If there is an error – you should only see it in Developers Tools in your browser.
Try adding:
$('#postForm').submit(function(e) {
e.preventDefault();
...
}
So that browser doesn't post the form instead of your AJAX call. Also try fixing your header case: X-CSRF-TOKEN to X-CSRF-Token
Also, your postMessage() method doesn't return anything at all. You should probably notify the user of the result there or just return $newMessage.

Related

Laravel Ajax Update 1 Column of record

I have a user schedule record that I can update easily without one form field called disabled_dates. disabled_dates is setup to store an array of dates a user can add one at a time. What I did was add a form field with its own button using a javascript function disable() in the onclick attribute to update the record.
<div class='input-group text-center'>
{!! Form::text('disabled_dates', null , ['class' => 'form-control text-center datetimepicker15', 'id' => 'disable_date', 'placeholder' => '']) !!}
<span class="input-group-btn">
<button type="button" onclick="disable();" class="btn btn-fab btn-round btn-success">
<i class="material-icons">add</i>
</button>
</span>
Then created the disable(); like so
function disable() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'PUT',
url:'/schedule',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
}
The controller function used is
public function add_blocked_day(Request $request)
{
$schedule = User::find(auth()->user()->id)->schedule;
$current_blocked_dates = $schedule->disabled_dates;
$schedule->disabled_dates = $current_blocked_dates. ','.$request->blocked_date;
$schedule->save();
exit;
}
All Im getting now is too many redirects. The solution Im thinking is to seperate disabled_dates and enclose in its own form tags, because its calling the original form route somehow
I got it to work by changing the function to this
$(document).on("click", ".add-day" , function() {
var CSRF_TOKEN = '{{ csrf_token() }}';
var disabled_date = document.getElementById('disable_date').value;
$.ajax({
type:'POST',
url:'schedule/blocked-day',
data:{_token: CSRF_TOKEN, blocked_date: disabled_date},
success:function(response) {
console.log(response);
}
});
});

Laravel Ajax Failed loading Post

i am trying to update data but i am getting error, failed loading post.
AJAX code:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("run");
// e.preventDefault(e);
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("updated");
},
});
});
});
view:
when i try all text field in div i get error failed loading post,
<div id="update-form">
//all text fields
<button type="button"name="id" value="{{#$teacher->id}}" id="update-data" >UPDATE</button>
</div>
but when i put everything in form my data is being updated correctly, but in this case ajax code is totally ignored and only last record is updating.
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}}
#endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Console Error:
app.js:10216 POST http://todolist.local/teachers/729 405 (Method Not Allowed)
app.js:10216 XHR failed loading: POST "http://todolist.local/teachers/729".
javascript?v=1567677915:4 XHR finished loading: GET "http://todolist.local/_debugbar/open?op=get&id=X15228e3cd6c2213f70bded7c0a69583b".
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
web.php:
Route::get('/', 'TeachersController#index')->name('home');
Route::resource('teachers', 'TeachersController');
Update your ajax request as below:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "PUT",
/*Your logic*/
});
});
});
View
<form action="#if(isset($teacher)) {{route('teachers.update', $teacher->id)}} #else {{route('teachers.store')}} #endif" method="post" id="update-form" autocomplete="off" enctype="multipart/form-data" >
{{method_field('PUT')}}
{{ csrf_field() }}
<button type="submit" name="id" value="{{#$teacher->id}}" id="update-data" > UPDATE</button>
</form>
Try this..
ajax post caused the webpage to reload before I could get a result, therefore.

Laravel live ajax search - token mismatch

I am making a live search where user can search for business.
This would be done using ajax and display results however I get an error that there is an TokenMismatchException.
Here's my code:
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
Controller:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
Route::
Route::get('/', function () {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
Route::get('tfgm', 'GuzzleController#tfgm')->name('tfgm');;
Route::get('odeon', 'GuzzleController#odeon')->name('odeon');;
Route::get('chronicle', 'GuzzleController#oldham_chronicle')->name('chronicle');;
Route::get('smokeyard', 'GuzzleController#smokeyard')->name('smokeyard');;
Route::get('profile/', 'ProfileController#checkid')->name('profile');;
Route::get('create/business', 'BusinessController#addBusiness')->name('createBusiness');
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route::post('/searching/{search}', 'SearchController#search');
Route::post('update', 'ProfileController#updateProfile');
Route::post('create', 'BusinessController#createBusiness');
Route::post('image', 'ImageController#image');
Route::post('test2', 'ImageController#gallery');
Route::post('markers', 'BusinessController#saveMarkers');
Route::post('reviews', 'BusinessController#saveReviews');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/redirect/{provider}', 'SocialAuthController#redirect');
Route::get('/callback/{provider}', 'SocialAuthController#callback');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
#include('results')
</div>
</div>
</form>
Your line must be
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In your ajax code you have written X-CSRFToken that is wrong. Correct is X-CSRF-TOKEN
Always use below code in you script file
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Change X-CSRFToken to X-CSRF-TOKEN

Laravel AJAX Form 405 Error

I'm receiving this error when attempting to submit via AJAX. When not using AJAX, the form submits just fine to it's specified url. I've read this error can happen because the form is trying to submit in the browser along with the AJAX request. I've tried using onsubmit="event.preventDefault()".
ROUTE:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
FORM:
<form id="post" role="form" action="{{ route('post.message', ['id' => $user->id]) }}" onsubmit="event.preventDefault()">
<div class="feed-post form-group{{ $errors->has('post') ? ' has-error' : ''}}">
<textarea class="form-control feed-post-input" rows="2" id="postbody" name="post" placeholder="What's up?"></textarea>
<div class="btn-bar">
<!-- <button type="button" class="btn btn-default btn-img btn-post" title="Attach an image"><span class="glyphicon glyphicon-picture"></span></button> -->
<!-- <input type="file" id="img-upload" style="display:none"/> -->
<button class="btn btn-default btn-post" title="Post your message"><span class="glyphicon glyphicon-ok"></span></button>
</div>
#if ($errors->has('post'))
<span class="help-block">{{ $errors->first('post') }}</span>
#endif
</div>
<input type="hidden" name="_token" value="{{ CSRF_token() }}">
</form>
CONTROLLER:
public function postMessage(Request $request, $id)
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
if(Request::ajax()){
Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
JS:
$('#post').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
});
try this, remove
onsubmit="....." attribute from form
and update your submit method like this
$('#post').submit(function(event){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
var postRoute = '/post/'+profileId;
var dataString = "body="+body+"&profile_Id="+profileId;
$.ajax({
type: "POST",
url: postRoute,
data: dataString,
success: function(data){
console.log(data);
}
});
//this will prevent your default form submit
event.preventDefault();
});
I hope this will work for you

Laravel 5 missmatch token in sending email

i'm using ajax to send email so i my problem is if i dont have
{!! csrf_field() !!}
in view i will get the token missmatch error.If i add input hidden token in view i will get this error
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in
mailbox given [] does not comply with RFC 2822, 3.6.2.
How can i fix it.Thanks for help.
here it's view
<form action="{{ url('/findpass')}}" method="POST" id="forgotpassForm">
{!! csrf_field() !!}
<div class="form-group">
<input class="form-control input-lg" placeholder="E-mail" name="emailForgot" type="email" id="emailForgot" required>
</div>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="forgotpassBtn" value="Send email">
</form>
Ajax
$(document).ready(function() {
$('#forgotpassBtn').click(function() {
event.preventDefault();
var email=$("#emailForgot").val();
var _token = $("input[name='_token']").val();
$.ajax({
url: '/findpass',
type: 'POST',
data:{
email:email,
_token : _token
},
success:function(data) {
alert(data.mess);
$("#forgotpass")[0].reset();
},
error:function() {
alert("Error");
}
});
});
});
Controller
public function resetPass()
{
$emailForgot=Input::get('emailForgot');
$user= User::where('email', '=' , $emailForgot)->first();
$data=['username'=>$user -> username,'email'=>$user -> email,'token'=>$user -> remember_token];
Mail::send('ui.mail.reset',$data, function ($m) use ($user) {
$m->from('ngohungphuc95#gmail.com', 'Reset password');
$m->to($user->email, $user->full_name)->subject('Email reset password');
});
return response()->json(array('mess'=>'Mail send'));
}
Add the csrf without blade and add an id by yourself. Get the value of csrf value by id using jquery. Here is how you can do this.
Change {!! csrf_field() !!} to:
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token"/>
And Change this line of ajax code:
var _token = $("input[name='_token']").val();
To:
var _token = $('#token').val();
May be this is not the best way. But I solved my problem with this procedure.
You could also add a global csrf token to all ajax calls like this
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') },
});
});
Then just override the tokensMatch() method of the VerifyCsrfToken token to also look for the ajax header
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}
After this all your ajax calls will automatically pass csrf checks and be secure.
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
The above error is because you haven't configured a from address in config/mail.php. It is set to null by default, but should be a valid email address:
'from' => ['address' => 'user#example.com', 'name' => null],

Resources