Laravel 5.6 Ajax post data - php

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'.

Related

The POST method is not supported for this route even though i am using get method

my route is
Route::get('functionvalueupdate',[\App\Http\Controllers\AdminController::class,'functionvalueupdate'])->name('functionvalueupdate');
in script
$.ajax({
type: "GET",
url: "{{route('functionvalueupdate')}}",
data: {
id: id,
},
success: function(res) {
}
}
)
controller
public function functionvalueupdate(Request $request)
{
dd($request);
}
Console log error
allfunctionalarea:1 POST http://localhost/FESROZGAR/allfunctionalarea 405 (Method Not Allowed)
still i get this error The POST method is not supported for this route. Supported methods: GET, HEAD.
Something is not right here.
Your route, show that GET to functionvalueupdate .
However, your console log show at different route. Which is
http://localhost/FESROZGAR/allfunctionalarea . I didn't see any route to functionvalueupdate.
Or something like http://localhost/FESROZGAR/functionvalueupdate .
Please double check your POST or GET to the correct route. You can inspect element to see if the {{ route('functionvalueupdate') }} print the right route.
Change get to post in route as given below:
Route::post('functionvalueupdate'[\App\Http\Controllers\AdminController::class,
'functionvalupdate'])->name('functionvalueupdate');
Also change ajax type from get to post and don't forget to include csrf token in ajax request.
$.ajax({
type: "POST",
url: "{{route('functionvalueupdate')}}",
data: {
id: id,
"_token": "{{ csrf_token() }}",
},
success: function(res) {
console.log(error);
},
error:function(error) {
console.log(error);
}
}
)
Just try this for make the debuging better
$.ajax({
type: "GET",
url: "{{route('functionvalueupdate')}}",
data: {
id: id,
},
success: function(res) {
console.log(res);
},
error:function(error) {
console.log(error);
}
}
)
And please add the console.log error in your question and add your controller to the your question too

405 error in laravel 5.6

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

Laravel 5.6 ajax post without form

I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.
Maybe you just rewrite the "select2" name end of the route to "select"?
I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});

Laravel 5.5 : 419 unknown status with AJAX

I am requesting POST :
Route :
Route::post('/register','CommonController#postRegister')->name('register');
CSRF Meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
$("#submitSalonForm").click(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/register",
type: "post",
data: new FormData($('form')[1]),
cache: false,
contentType: false,
processData: false,
success:function(response) {
return alert('Form 2 submitted');
}
});
});
And the exception :
The exception comes sometimes and sometimes the code runs smoothly, I have no idea what am i missing here.
Change ajax method from post to get
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Ajx call:
let formData = $('form').serializeArray();
$.ajax({
url: "/register",
type: "POST",
data: {formData, "_token": $('#token').val()},
cache: false,
datatype: 'JSON',
processData: false,
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
Your route is get
Route::get('/register','CommonController#showRegister')->name('register');
Ajax call is making a post request, laravel sqwaks with a http exception.
EDIT:
Laravel 419 post error is usually related with api.php and token authorization
So try to include the token on ajax body instead like above.
In addition to putting the crsf-token value in the header meta tag you need to pass it through in your AJAX requests like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
No need to setup ajax separately. Laravel automatically generates a CSRF "token" for each active user session managed by the application. Get the token with this:
var token = "{{ csrf_token() }}";
Pass the token in data
var token = "{{ csrf_token() }}";
var formData = new FormData($('form')[1])
$.ajax({
url : '/register',
data : {_token:token,formData:formData},
type: 'post',
...
})
Well, I know I am too late, but I did face the exact issue you face.
I was 100% sure that the token has been sent with the request, but the issue is still.
So, after too many searches I finally got it fixed by following these steps:
php artisan config:clear
php artisan view:clear
php artisan route:clear
php artisan cache:clear
php artisan clear-compiled

Ajax Call not returning successful but script executes

I have an Ajax call made using a custom callback function invoked from Redactor.JS - The Ajax itsself posts data to a function which stores the information in a database. I know the POST is being made and the script executing because the information itsself is being stored correctly however the .success function of the ajax call is not completing and I cannot for the life of me figure out why.
My call is in full below. 'data' is not logged in the console and I have attempted all manner of alerts etc
$.ajax
({
url:'<?php echo base_url('cms/page/'.$this->type.'/create/'.$this->page_id); ?>',
type:'post',
dataType: 'json',
data: 'content=' + $('#redactor').redactor('get')+'&status=draft&title='+ $('#title').val() +'&sub=' + $('#sub').val()+'&id=<?php echo $this->page_id;?>&tags='+$('#tags').val()+'&dynamic_save=true&post_page=true',
cache: false
}).success(function ( data )
{
console.log( data );
});
I think you need to test this code which is working for me
var config = {
url: YOUR_URL,
type: 'post',
data: {"key1" : "val1","key2" : "val2"},
// headers: HEADERS(optional),
dataType : 'json'
success: function(data){
console.log(data);
// handle success response
}
};
$.ajax(config);
OR you can use .done method intead of .success see this

Categories