“405 Method not allowed” on external js file in Laravel 5.8 - javascript

I have small laravel project working on ajax. Below is laravel route
Route::group(['prefix' => 'api'], function(){
Route::group(['prefix' => 'location'], function(){
Route::post('province','Api\LocationController#Province')->name('api.location.province');
});
});
And function in controller.
public function Province(Request $request){
$provicnes = Province::get();
return response()->json($provicnes);
}
I can use ajax to call from blade and I can get the correctly result. Below is ajax code.
var route = {
url: "{{ url('/') }}",
token: $('meta[name="csrf-token"]').attr('content')
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"{{ route('api.location.province') }}",
method:"POST",
success:function(response){
console.log(response)
}
});
Then, I create external js file and link to blade.
<script type="module" src="{{asset('assets/js/plugins/apps/location.js')}}"></script>
Then, use same the upon ajax code in jquery document-ready function.
$( document ).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': route.token
}
});
$.ajax({
url:`${route.url}/api/location/province/`,
method:"POST",
success:function(response){
console.log(response)
}
});
});
But I got '405 Method not allowed' instead. Any advise or guidance would be greatly appreciated, Thanks.

You can remove route name and simple use this line.
Route::post('province','Api\LocationController#Province');
Change your url to
$.ajax({
url:`${route.url}/api/location/province/`,
...
});
Or, assuming you have declare also the url in the route array.
var route = {
url: "{{ url('/') }}",
token: $('meta[name="csrf-token"]').attr('content'),
provinceUrl: "{{ route('api.location.province') }}"
};
and use it in the url.
$.ajax({
url:`${route.provinceUrl}`,
...
});

Related

How can I send JSON data from local storage to controller in Laravel?

I want to send the json data from view to controller using ajax. How can I achieve that?
The data in local storage is
[{"productId":2,"productCost":"630","productQty":"3"}]
Ajax
function saveData(){
const localStorageData=localStorage.getItem('myItems');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method:"POST",
url: "{{route('user.plan.insertData')}}",
dataType: "json",
data:{localStorageData:localStorageData,
},
success:function(data){
alert(data);
}
});
}
Controller
function insertData(Request $request)
{
$localStorageData = $request->input('localStorageData');
print_r($localStorageData);exit;
}
correct your ajax like this :
data:{
localStorageData: localStorageData,
'_token' : '{{ csrf_token() }}'
},
and also change the controller like this :
$localStorageData = $request->localStorageData;
remember to add #csrf inside (at the beggining) the form tag.
it depends on that what localStorageData really is. Depends on
it, you can work with it. if it is a string , no problem but if it is
an array, you should do different thing ...

Send Request In Laravel Using AJAX GET Method

Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});

405 Method Not Allowed for POST and PUT in laravel application

I'm trying to drop and resize an event in fullcalendar in laravel, but when I move the event, I have 405 Method Not Allowed error message!..
My web.php file:
Route::get('calendar', 'FullCalendarController#index');
Route::get('/load-events', 'EventController#loadEvents')->name('routeLoadEvents');
Route::put('/events-update', 'EventController#update')->name('routeEventUpdate');
My blade.php file:
<div id='calendar'
data-route-load-events="{{route('routeLoadEvents')}}"
data-route-events-update="{{route('routeEventUpdate')}}"></div>
My .js file:
$(function (){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
function sendEvent(route, data_){
$.ajax({
url: route,
data: data_,
method: 'POST',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
}
function routeEvents(route){
return document.getElementById('calendar').dataset[route];
}
eventDrop: function(element){
let start = moment( element.event.start ).format("YYYY-MM-DD HH:mm:ss");
let end = moment( element.event.end ).format("YYYY-MM-DD HH:mm:ss");
let newEvent = {
_method: 'PUT',
id: element.event.id,
start: start,
end: end
};
sendEvent(routeEvents('routeEventUpdate'), newEvent);
},
So there are really only two types of request that Laravel really understands:
POST & GET
A PUT request is a POST request with a method of PUT.
What laravel is looking for is a _method parameter in the request telling it what type of request this is. in your case _method: PUT.
Try this:
$.ajax({
url: route,
data: data_,
method: 'PUT',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
You put your "put" method in your payload-data, this wont be recocnized by the AJAX Function. Try adding the method as an Argument
function sendEvent(route, data_, sendMethod){
...
method: sendMethod,
...
And call i via
sendEvent(routeEvents('routeEventUpdate'), newEvent, 'PUT');

laravel ajax return 405

I'm trying to send data with ajax t controller and i get 405 error
Code
JS
$(document).ready(function(){
$('body').on('click', '.addbundlebutton', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
e.preventDefault();
var data= [];
$("input:checkbox[name=bundleProducts]:checked").each(function(){
data.push($(this).val());
});
// data are like ['41', '46'] in console //
$.ajax({
type: "post",
url: "{{ url('testadd-bundle') }}",
data: JSON.stringify(data),
success: function (data) {
console.log(data.success);
$(".addbundlebutton").remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
Route
Route::post('/add-bundle', 'frontend\BundleController#add');
Controller
public function add(Request $request){
//testing data...
$data = $request->all();
return response()->json($data);
}
Screenshot
Any idea?
You use this URL: url: "{{ url('testadd-bundle') }}",
But your route is set to be:
url('/add-bundle')
So try that instead. 405 means method not allowed, which means you try post on a get route for example.

Is it possible to insert data with ajax request by only using the csrf field instead of token?

I'm trying to insert data with CSRF field. I really don't have the idea of CSRF token. (new to laravel). I'm getting unknown status error in /classwork/insert.
//This is my ajax function: I really can't understand what is wrong with the code.
Is it possible to do ajax calls with only using {{csrf-field}}
function insertData(e){
e.preventDefault();
var data = $(this).serialize();
$.ajax({
url: '/classwork/insert',
method: 'post',
data : 'data',
success:function(data){
console.log(data);
}
});
}
//This is my controller and Route:
public function insertTask(Request $request){
$task = new Task;
$task->task = $request->task;
$task->save();
}
//this is my route
Route::post('/classwork/insert', 'TaskController#insertTask');
Make a genric ajaxRequest function. Add this to meta
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in your global ajax function do this;
public function ajaxRequest(options){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: option.url,
method: option.method,
data : option.data,
success:function(data){
console.log(data);
}
});
}
Try using this way
Add this before ajax calling
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Please always add this meta tag in main blade page
<meta name="csrf-token" content="{{ csrf_token() }}">
And instead of old scholl jquery ajax.. just use Axios. simple and very easy. it already detect the csrd-token meta tag. so no need to do in the form or header
change this
$.ajax({
url: '/classwork/insert',
method: 'post',
data : 'data',
success:function(data){
console.log(data);
}
});
to this
axios.post('/classwork/insert', data)
.then(function(response) {
console.log(response);
});

Categories