I'm developing an application with Laravel 5.1 and I have a problem when sending ajax petition I have the next code:
View for Create:
{!!Form::open()!!}
<div class="form-group">
{!!Form::label('genero','Genre:')!!}
{!!Form::text('genre',null,['id'=> 'genre','class'=>'form-control'])!!}
</div>
{!!link_to('#', $title = 'Create', $attributes = ['id'=> 'create','class'=>'btn btn-primary'], $secure = null)!!}
{!!Form::close()!!}
Ajax Petition:
$("#create").click(function(){
var genre = $("#genre").val();
var route = "http://localhost:8000/genre";
$.ajax({
url: route,
type: 'POST',
dataType: 'json'
data: {genre : genre}
});
})
In my Routes:
Route::resource('genre','GenreController');
But when send the petition I have the next error:
POST http://localhost:8000/genre 500 (Internal Server Error)
Thanks.
In default template , add meta tag
<meta name="_token" content="{!! csrf_token() !!}"/>
Then add script code :
<script type="text/javascript">
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
</script>
Then you can use ajax call...as normal
My solution was the next code:
$("#registro").click(function(){
var data = $("#genre").val();
var route = "http://localhost:8000/genre";
var token = document.getElementById('token').value
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: 'POST',
dataType: 'json',
data: {data : data}
});
});
Related
Can someone please show a Laravel 5.7 post ajax example with a full-working minimum example in a blade template? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
You can do something like this,
web.php
Route::post('/admin/order/{id}', 'OrderController#edit')->name('admin.order.edit');
blade.php
$(document).on('click', '.delete-button', function (e) {
e.preventDefault();
var orderId = 1
$.ajax({
type: 'post',
url: '/admin/order/' + orderId,
data: {
'_token': $('input[name=_token]').val(),
'data_one': 'dataone',
},
success: function () {
toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
toastr.error('Something Went Wrong !');
}
});
});
$.ajax({
url: 'http://some.working/url',
type: "POST",
data: $('#formContainer').serialize(),
success: function (response) {
console.log('Success', response);
},
error: function (response) {
console.log('Error', response);
}
});
The data can be produced in many ways for example
1. Using serialize() method as shown in the above example.
2. Using FormData():
for example
var data = new FormData($('#formContainer'));
In both of the above example, one thing compulsory is that your form
must contain csrf field. which can be provided using any of the
following methods:
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
or
{{ csrf_field() }}
or even more simply by just using
#csrf
in some where in your form.
In case you are not using any form, you can create the data object by
yourself like this
var data = {
_token: '{{ csrf_token() }}',
data1: 'Value1',
data2: 'Value2',
data3: 'Value2'
}
Define a Web Route
Route::get('currencies/fiat/changeStatus','FiatCurrencyController#changeStatus')->name("currencies.fiat.chanageStatus");
Call this function on click onclick="changeStatus(1,0)"
function changeStatus(id,status){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/currencies/fiat/changeStatus',
type: 'GET',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN,cid:id,status:status},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data);
}
});
}
That's it all Done.
$(document).ready(function(){
/* In laravel you have to pass this CSRF in meta for ajax request */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/* change in website layout base on click */
$('#user_view').on('click',function (e){
e.preventDefault();
$('.loading_screen').show();
var val = $(this).data('id');
$.ajax({
url: base_path + 'user/changeview/'+val,
type: "POST",
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.SUCC_FLAG == 0){
window.location.href = site_url;}
else{
/* for console error message. */
console.log(obj.MSG);}
$('.loading_screen').hide();
},
error: function () {
alert("server error");
}
});
});
});
Hey it's a working code and i hope this will works for you.
I'm working on Laravel and trying to send a variable to a controller using AJAX, but the request is changing to GET!
AJAX
function fetchTasks(email) {
$.ajax({
method: 'POST',
dataType: 'json',
url: '/teamwork',
data: {_method: 'POST', email : email},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
Routes.php
Route::any('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
When i change the route method to post, it shows a 405(Method Not Allowed)
When i dd($request) in my controller, this is what i get
image
So, why my Ajax request doesn't work ?
EDITED:
I've modified my code to the following
function fetchTasks(email) {
console.log(email);
var token = "{{ csrf_token() }}";
$.ajax({
method: "POST",
url: "teamwork",
data: {
_token:token,
'email': email
},
contentType: "application/json",
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
},
complete: function () {
window.location.href = '{{route("testTRoute")}}';
}
});
}
It's still sending an empty GET request. Output from console is the following:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Based on ajax documentation you should use type param instead method.
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Have u tried this?
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url:'teamwork' ,
type:'post',
data: { email : email},
method: 'POST',
dataType: 'json',
success:function(result){console.log(result);}
});
Route
Route::match(array('GET','POST'),'/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
If you want to send 'email' as a route parameter but don't want to show it in browser's address bar, you can do it as below.
Sending data through a form
At you blade.php
<form action="{{route('testPRoute')}}" method="POST">
#csrf
<!--
Set your email name or variable in input's value attribute. Like
<input type="text" name="email" value="email">
or
<input type="text" name="email" value="{{$email}}">
or -->
<input type="hidden" name="email" value="email">
<button type="submit">Go to Route</button>
</form>
At your Web.php
Route::post('/teamwork', 'TeamworkController#teamwork')->name('testPRoute');
At your Controller
public function teamwork(Request $request)
{
$email = $request->email;
return $email;
}
After a long time of debugging, i have found that my problem was with the routing. I had two routes, GET and POST with the same name. That's why it was always sending a GET request.
im sending a form data via ajax to the server using laravel 5.6
when sending the data to the server, i have specified the method of ajax to POST and the routing method in web.php to post too, the problem is, ajax sendS the form data with GET method not POST. what should i change???
ajax code
var form = $('#personPersonalInfoForm')[0];
var formData = new FormData(form);
$.ajax({
url:"/addNewPerson",
Type: "POST",
data: formData,
contentType: false,
processData: false,
success: function(data)
{
alert(data);
}
});
web.php code
Route::post('/addNewPerson', 'adminController#addNewPerson');
Here is an example of working code using the FormData.
Using the "method" configuration instead of "type".
var form = document.getElementById("ajaxForm");
var formData = new FormData(form);
var url = form.action;
$.ajax({
method : 'POST',
url : url,
data : formData,
contentType: false,
processData: false
}).done(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
Dont forget to add the CSRF token in the form.
<form method="POST" action="/addNewPerson" id="ajaxForm">
#csrf
...
</form>
Or configure the ajax method from the start with it.
in the < head> add
<meta name="csrf-token" content="{{ csrf_token() }}">
and in the JavaScript add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
web.php
Route::post('/addNewPerson', 'adminController#addNewPerson')->name(admin.add_new_person);
in your adminController :
public function addNewPerson(Request $request){
// you can check request parameters
//return response()->json($request->all());
// add new person code here ...
return response()->json(array('status'=>'success','message'=>'person added'));
}
your ajax code should be :
$.ajax({
url:"/addNewPerson",
type: "POST",
data:$('#personPersonalInfoForm').serialize(),
dataType:'json',
contentType: 'application/json',
success: function(data)
{
alert(data);
},
error:function(){
alert('ERROR');
}
});
I tried to send data to a page with Ajax post without form but it doesn't work.
I guess my problem come from crs but I won't be able to find how to make it work.
In the header of my page, I have ;
<meta name="csrf_token" content="{{ csrf_token() }}">
Then, for this example, I have a datatable with reorder plugin. When reorder event is trigger, I use Ajax call (but my problem happen no matter what I do to send post Ajax except with form).
table{{$batiment->id}}.on( 'row-reorder', function ( e, diff, edit ) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'etages/form',
type: 'POST',
data: {item_id : 1},
dataType: 'json',
success: function( data ) {
console.log(data);
}
})
});
My route to form :
Route::post('/etages/form', ['as' => 'etages.form', 'uses' => 'Copro\EtageController#form']);
And my function form from my controller (this function work well with form post data) :
public function form(Request $request)
{
$request->flash();
return response()->json([
'error' => 'false'
]);
}
But every time I tried post data without form, no matter what trigger I use (datatable, onclick...) I have this message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
On chrome console I can see my post data, but on laravel's error page, post data is empty. I don't know if it's normal.
Someone can help me with that problem ? I can't always use get to send this kind of data.
Thank for your help.
Method 1:
var csrf = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: '/etages/form',
type: 'POST',
data: {item_id : 1, '_token': csrf},
dataType: 'json',
success: function( data ) {
console.log(data);
}
})
Method 2:
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': decodeURIComponent(/XSRF-Token=([^;]*)/ig.exec(document.cookie)[1])
}
});
$.ajax({
url: '/etages/form',
type: 'POST',
data: {item_id : 1},
dataType: 'json',
success: function( data ) {
console.log(data);
}
})
your link 'etages/form' , have you defined it in a api route.
if you have defined in a api route, then it should be like this '/api/etages/form'.
When I use a POST method with the following ajax request, it throws a "Method not allowed" error. If I use the form POST without using ajax, it goes to the proper method.
In Router.php:
$this->post('TestPost','DashboardController#TestPostMethod');
In View, the ajax request is:
$.ajax(
{
type: "POST",
url: 'TestPost',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
alert('hid post');
SetHotandWorstData(data,'hotquantity');
},
error: function (msg) {
alert('error');
alert(msg.responseText);
}
});
In Controller:
function TestPostMethod(Request $request)
{
$hotworstsalesdata = DB::table('100_INVOICEDETAIL')
->select( '100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME',
DB::raw('SUM("100_INVOICEDETAIL"."QTY") as
salesqty'), DB::raw('SUM("100_INVOICEDETAIL"."AMT") as salesamt'))
->groupBy('100_INVOICEDETAIL.ITEMCODE','100_INVOICEDETAIL.ITEMNAME')
->orderBy('salesqty')
->take(10)
->get();
return Datatables::of($hotworstsalesdata)->make(true);
}
you should pass "_token" in POST data. Laravel use token for cross-site request forgery (CSRF) attacks. use following code in your AJAX request
data: { _token: "{{ csrf_token() }}" }
Updated answer:
I have re-create same scenario on my system with laravel 5.4 and it's working for me.
my route (web.php) code is:
Route::post('/test_post', 'DashboardController#getData');
Javascript code is:
<script type="text/javascript">
$.ajax({
type: "POST",
url: '{{ url('/') }}/test_post',
data: { _token: "{{ csrf_token() }}" },
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (data) {
console.log(data);
},
error: function (msg) {
console.log(msg.responseText);
}
});
</script>
DashboardController file is:
public function getData(Request $request) {
print_r($request);
}
Recently I got error with DELETE method ! I fixed by setting csrf token in html header and get in ajax . Hope this can solve your problem ..
<html>
<header>
<meta name="csrf-token" content="{{ csrf_token() }}" />
In ajax,
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});