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.
Related
I get an 405 (Method Not Allowed) error when sending an AJAX request. I've been working hard looking for a solution but still receive the same error.
I have added this inside the header section:
<meta name="csrf-token" content="{{ csrf_token() }}">
And this is the AJAX code:
function AjaxCall() {
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
header: {
'X-CSRF-TOKEN': token
},
data: {
_token: token,
_method: "PUT",
},
success: function() {
console.log('success');
}
});
}
Laravel code:
try {
$lastNum = DB::table('no_antrian')->select('antrian')->first();
if (!is_null($lastNum))
{
$data = DB::table('no_antrian')->update(['antrian' => $lastNum + 1]);
}
return response()->json(['success' => 'Sukses']);
}
catch(\Exception $e) {
return response()->json(['error' => 'failed']);
}
Route:
Route::post('antrian/insertNum', [AntrianController::class, 'getQueueNum']);
please Remove put method inside data
var token = $('meta[name="csrf-token"]').attr('content');
let myData = $('form').find('input[name="my_data"]').val();
$.ajax({
url: 'insertNum',
type: 'POST',
dataType: 'json',
data: {
_token: token,
my_data: myData
},
success: function() {
console.log('success');
}
});
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');
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}`,
...
});
I am trying to make a comment form which adds a comment in array of blog schema
but when I am using ajax it is giving undefined below the places where I have console log and when I am using simple post request it is working fine.
I am using mongoose, nodejs , express, jquery ajax
my script is as follows
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
function addNewComment(data){
console.log(data);
}
my routes is as follows
//add comments
router.post('/addComment',function(req,res,next){
console.log(req.body.comment+" "+ req.body.userId+" "+req.body.postId);
var newComment = {
'text': req.body.comment,
'author': req.body.userId
}
Post.addComment(req.body.postId, newComment, function(err,comment){
if(err) throw err;
console.log(comment);
res.send(comment);
});
});
and my mongoose schema is
//add comments
module.exports.addComment = function( postId, newComment, callback){
var query = { '_id': postId};
console.log('postid: '+postId+" newcomment: "+newComment.text+ " "+newComment.author);
Post.findOneAndUpdate( query, { $push:{'comments': newComment} }, {new:true} , callback);
}
That's because data is not defined in ajax call ,
use following provide the frm is the actallu form or use
use data : form name.serialize()
var frm = $('#commentForm');
frm.submit(function (e) {
e.preventDefault();
console.log('clicked');
$.ajax({
data : $(this).serialize(),
type: 'POST',
url: "/blog/addComment",
contentType: "application/json; charset=utf-8",
dataType: 'json'
})
.done(function(data) {
addNewComment(data);
})
.fail(function() {
console.log("Ajax failed to fetch data");
});
});
I'm trying to push some data via ajax in Laravel. Unfortunally it does not work. When I was watching at the network traffic, i found this:
Request Method:POST
Status Code:302 Found
I'm trying to get data from a JSGrid, which works fine. The data-object is filled. I checked it. For testing I just returned a short message in my controller. But it's not even called when I send the POST request...
Here is my code
Javascript:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
$('#save_list').click(function (e) {
e.preventDefault();
var url = '{{ route("account.save_accounts_to_user") }}';
var post = {};
post.account_list = $("#jsGrid").jsGrid("option", "data");
$.ajax({
type: "POST",
url: url,
dataType: 'JSON',
data: post,
cache: false,
success: function (data, textStatus, jqXHR) {
console.log(textStatus + " - " + data);
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText + textStatus + " - " + errorThrown);
}
});
return false;
});
Route:
Route::post('save_accounts_to_user', ['as' => 'account.save_accounts_to_user', 'uses' => 'AccountController#saveAccountsToUser']); //ajax request
Controller:
/**
* Save all used accounts for a user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function saveAccountsToUser(Request $request)
{
$response = array();
$response["status"] = "ok";
$response["message"] = trans('account.accounts_saved');
return \Response::json($response);
}
I was expecting that I will get the JSON text from the controller method as the responsemessage. But instead i get redirected without calling the wanted method.
I don't know what happens there. There is no middleware assigned to this route, which could be the reason for this redirect.
Do you have an ideas?
After all it was a middleware of an outter group which was redirecting the request -.-
May be 'X-CSRF-Token' used by you instead of 'X-CSRF-TOKEN' mentioned in Laravel docs is the issue here? Try to follow the Laravel docs completely.Please refer below link.
https://laravel.com/docs/5.3/csrf
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
add this code:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
after this:
var url = '{{ route("account.save_accounts_to_user") }}';
Use headers in AJAX call
Example:
$.ajax({
type: "POST",
url: link, // your link
data: DataObject, // data to pass
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (result) {
}
});