Laravel POST via Ajax - php

I'm trying to submit a form via ajax, but I'm always getting internal server error
Here is my form code
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<!-- Solo moderador -->
<div class="card-panel">
#if(Auth::user()->permision->request == 1)
<p class="center">Observaciones del moderador:</p>
<textarea type="textarea" class="materialize-textarea" name="observations" id="updateObservations"></textarea>
#else
<div class="center">
<input type="checkbox" id="userVerify" class="filled-in">
<label for="userVerify">Problema solucionado :)</label>
</div>
</div>
#endif
{!! Form::close() !!}
Here is my route
Route::post('request/update', 'RequestsController#postUpdateRequest')->name('request.update');
Here is my Ajax method
$.ajax({
type: "post",
dataType: "html",
url: 'request/update',
data: $("#form").serialize(),
success: function (response) {
// write here any code needed for handling success
console.log("se envio");
}
});
and here is my method in the controller
public function postUpdateRequest(Request $request)
{
if($request->ajax())
{
// Obteniendo registro de la petición
$petition = Petition::where('id', $request->id)->first();
// Guardando
$petition->fill($request->all());
$auditConfirm = $petition->isDirty();
$petition->save();
// Guardando registro de auditoría
if($auditConfirm){
AuditsController::postAudit($this->action_id_update);
}
}
}
EDIT: This is the console output

Include this in your form:
echo Form::token();
Basically Laravel expects a CSRF token, middleware makes sure that token sent from form matches the token created before it.
If you don't want to add that on forum, you can add that in AJAX setup:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
..and have this in the HTML page header:
<meta name="csrf-token" content="{{ csrf_token() }}">

You are missing the CSRF token, Laravel has a method of handling this vulnerability via middleware, you have 2 options:
Add csrf token in html form:
{!! Form::open(['route' => 'users.add', 'id'=>'form']) !!}
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
Provide a global header when making a request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Read more

SOLVED:it seems that ive been missing the id value in the request all this time

Related

How to submit a blade.php form with AJAX

How should I handle the csrf_field() function when doing this with AJAX?
here is a link to the project repo.
Here is a link to the article which helped me write the code.
I'm pretty sure I don't have to make too many changes to the code to handle the forms with AJAX instead of regular blade.php form submissions, but I'm unsure of the implementation
<form id="add_item" method="POST" action="/item">
<div class="form-group">
<textarea name="item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button type="submit" >Add Item</button>
</div>
{{ csrf_field() }}
</form>
you can also put csrf-token in header file like this...
<meta name="csrf-token" content="{{ csrf_token() }}">
then give one unique id to submit button... then after in JavaScript detect that click event. then after call ajax on click event of submit button
$.ajax({
type: "POST",
// url: "{{ route('admin.users')}}" + id,
// url : '/admin/users/',
url: "{{url('admin/users/')}}", // you can pass url using url() OR as simple url OR Route name also
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') //get the Csrf token from header
},
data: { id: id, }, //pass here all data which you want to pass to controller
success: function (data) {
console.log(data);
}
});
get the csrf value using
var token = $('input[name="csrfToken"]').attr('value');
and append it to the header
$.ajax({
url: route.url,
data : JSON.stringify(data),
method : 'POST',
headers: {
'X-CSRF-Token': token
},
success: function (data) { ... },
error: function (data) { ... }
});
you can read more about it here https://stackoverflow.com/a/51964045/9890762
SOLVED.
I had to remove the 'type' attribute from the form as ajax is being used instead,
and ensure the ajax functions are at /public/js/file.js
Then, to make the changes available to the folder resources
npm run dev
<form id="add_item_form" action="/item">
<div class="form-group">
<textarea id="add_item_name" placeholder='Enter your item'></textarea>
#if ($errors->has('item_name'))
<span class="text-danger">{{ $errors->first('item_name') }}</span>
#endif
</div>
<div class="form-group">
<button id="ajaxSubmit_add">Add Item</button>
</div>
</form>

Laravel ajax request with csrf

I'm using Laravel 7.2.0, trying to send an ajax request but I have a problem.
I'm trying to pass the csrf token from the meta but it give me 419 error.
It only works if I add #csrf on the form as below, but the controller dont get an ajax request.
The form:
<form id="formto" method="POST" action="{{ route('selectedtodolist') }}">
#csrf
<p>{{$Todo->name}}</p>
<br>
<input id="id_todolist" name="id_todolist" value="{{$Todo->id}}" type="hidden">
<input type="submit">
</form>
Head:
#push('head')
<!-- Scripts ajax -->
<script src=" {{ asset('js/components/Selectedtodolist.js') }} "></script>
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}" />
#endpush
Jquery ajax:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(() => {
$("#formto").submit((e) => {
let that = e.currentTarget;
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
success: function() {
alert("work");
}
})
.done((data) => {
console.log(data);
})
And the controller: (give me 404 error cause of this 'if'):
public function __invoke(Request $request)
{
if ($request->ajax()) {
$this->validate($request, [
'id_todolist' => 'bail|required|email'
]);
return response()->json ();
}
abort(404);
}
route: Route::post('selectedtodolist', 'SelectedlistController')->name('selectedtodolist');
Thank you in advance

Laravel 5.3 Ajax url not found

I'm working on a screen with the following url http://localhost/npr/public/admin/athletes/test/143
On this screen, I've implemented the following dynamic droplist Ajax call that's not found:
$(document).ready(function() {
$('select[name="section"]').on('change', function() {
var sectionID = $(this).val();
if(sectionID) {
$.ajax({
url: './getSportPositions'+sectionID,
method: 'get',
//data: {"_token": $('#token').val()},
dataType: "json",
success:function(data) {
$('select[name="position"]').empty();
$('select[name="position"]').append('<option value="">'+ '-- Please choose one --' +'</option>');
$.each(data, function(i, position) {
$('select[name="position"]').append('<option value="'+position.name+'">'+ position.name +'</option>');
});
}
});
}else{
$('select[name="position"]').empty();
}
});
});
Route:
Route::get('getSportPositions{id}','HomeController#getSportPositions');
I've also tried with:
Route::get('/admin/athletes/test/getSportPositions{id}','HomeController#getSportPositions');
Is it due to athlete ID 143 in the calling URL? How do I fix this call?
It seems from the error that it's trying to access this route:
Route::get('/admin/athletes/test/{athlete}/', [
'uses' => 'HomeController#testAnAthlete',
'as' => 'admin.test_athlete'
]);
HTML:
<div class="form-group {{ $errors->has('position') ? ' alert alert-danger' : '' }}">
<label for="position" class="col-md-3 control-label">Position in Team</label>
<div class="col-md-6">
<select class="form-control" name="position" id="position">
#if (!$errors->has('position'))
<option selected value> -- select a team first -- </option>
#endif
</select>
</div>
#if ($errors->has('position'))
<span class="help-block">
<strong>{{ $errors->first('position') }}</strong>
</span>
#endif
</div>
When you are using Ajax you have to get url like
var APP_URL = $('meta[name="_base_url"]').attr('content');
also add this
<meta name="_base_url" content="{{ url('/') }}">
to head tag
then after you can use APP_URL
var url = APP_URL+"/getSportPositions/"+sectionID;
Additional from me. in laravel view :
<meta name="_base_url" content="{{ url('/') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
in addition to #Nikhil Radadiya answer, because using jquery mean you wait for page ready, you can use javascript :
var APP_URL = document.getElementsByTagName('meta')._base_url.content;
var APP_CSRF = document.querySelector("meta[name='csrf-token']").content; // javascript cannot use dash, else you can use csrf_token at meta name
then you can use in your ajax like :
$.ajax({
headers: {
'X-CSRF-TOKEN': APP_CSRF
},
url: APP_URL + '/your_ajax_path',
...
...
});
and make sure the url is loaded in your web route.
You could name the route and use BLADE to set a Javascript variable to that route.
For example:
Route::get('/', 'MyAmazingController#function')->name('my.awesome.route');
Then in your Javascript you can do something like:
url: '{{ route('my.awesome.route') }}';
If you have the javascript in a seperate file, you could create a constant in your view with routes in it.
val ROUTES = {
AJAX: '{{ route('my.awesome.route') }}'
}

Laravel 5: Ajax Post 500 (Internal Server Error)

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:
POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)
What's wrong with my code? Is it the javascript or the controller?
EDIT: I'm getting this in laravel.log
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Route
Route::resource('articles', 'ArticlesController');
Controller
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
);
return \Response::json($response);
}
jQuery
$(document).ready(function() {
$('#frm').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
console.log(data);
}
});
});
View
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<h1>Write a New Article</h1>
<hr>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
<h3 id="ajaxResponse"></h3>
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});
When you make a request via POST to a resource controller, it automatically calls store method:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
So, you just need to change ajax url to:
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles',
When you need to send the session token, you can add a global meta-tag like this is you website:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, just add the token via ajax's headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
That's what I got exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Htt‌​p\Middleware\VerifyCsrfToken.php:53
You're hitting Laravel's CSRF protection.
http://laravel.com/docs/5.1/routing#csrf-protection
You need to pass the hidden _token field's value. This can be done automatically on all jQuery-initiated AJAX requests by doing this in your application's JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').value()
}
});
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls.
I like to share this code to help someone to need ajax post and get with laravel
<<<<<<<<
POST
<<<<
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login4')}}',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
alert(data);
console.log(data);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::post('login4', function()
{
return 'Success! POST Ajax in laravel 5';
})->name('login4');
------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login2')}}',
type: "get",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
obj = JSON.stringify(data, null, " ");
var datito = JSON.parse(obj);
console.log(datito.response);
alert(datito.response);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::get('login2', 'WebController#login2')->name('login2');
-------------0----------------------
-------------0----------------------
<<<----<<Http\Controllers\WebController.php<<<<-----------<<<
public function login2(Request $datos) {
if ($datos->isMethod('get')) {
return response()->json(['response' => 'This is get method']);
}
return response()->json(['response' => 'This is post method']);
}
-------------0----------------------
-------------0----------------------
You can add your URLs to the VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification:
protected $except = [ "your url", "your url/abc" ];
Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,
<h6>ITEMS ORDERED:CLICK HERE</h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Now With Ajax
<script type="text/javascript">
function getcart(val) {
var alpha=val;
var token=document.getElementById('token').value;
$.ajax({
type:'post',
url:'/private/getcart',
data:{'alpha':alpha,'_token': token},//this _token should be as it is
success:function (result) {
alert(result);
}
});
}
</script>
In my laravel controller
public function getcart(Request $req)
{
return response ("its");
}

Ajax POST error using Laravel

I want to submit a form of checkboxes that represent the interests of an user. When clicking a checkbox, the value of the checked interest will be sent to the database "Followers" table and the user will begin following that interest. I couldn't find a way to have one form submit multiple rows, so i decided to make each checkbox a different form and use Ajax to send the information as the user goes through the form. However, When i attempt to make a POST using Ajax I get POST http://localhost/interest net::ERR_CONNECTION_REFUSED. or ERR 500. Can someone help me? I don't understand where i'm messing up. here is my code:
i have the meta tag
<meta name="_token" content="{{ csrf_token() }}"/>
html:
{!! Form::open(array('id'=> 'form2')) !!}
<div class = "form-group">
<div class="col-md-6">
{!! Form::label('title','Title:', ['class' => 'col-md-4 control-label']) !!}
{!! Form::checkbox('interest_id', '2', false, ['class' => 'formclick']) !!}
</div>
</div>
<input id = "submit" type="button" value="Click Me!" />
{!! Form::close() !!}
JS:
var base_url = 'http://localhost';
$('#submit').click(function(){
var interest = {
interest_id : $('.formclick').val()
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: base_url+'/interest',
data: interest,
dataType: 'JSON',
success: function() {
alert('new interest');
}
});
});
InterestController:
public function store(InterestRequest $interest)
{
$interest = new Follower(array(
'user_id' => $interest->get('interest_id'),
'follower_id' => Auth::id()
));
$interest->save();
}
Don't use the same variable name for an parameter and a local scope variable.
Are you using nginx or apache?
Have you setup your .htaccess file right?
What do you see when you go to http://localhost/interest/public
Enable the Laravel debug mode, there you have much more information which can be of help to you and us.
You should use proper path of URL to ajax call.
instead of use:
var base_url = 'http://localhost';
use:
var base_url = '{{ url() }}';
It will resolve your issue

Categories