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');
}
});
Related
On laravel.log I get this:
[2020-08-20 15:51:08] local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in /home/ialinves/public_html/cms/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php:53
On browser console I get this:
POST https://ial.pt/ajaxform 500 (Internal Server Error)
My code is:
$(document).ready(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var nom = 'teste';
$.ajax({
type: 'POST',
url: 'ajaxform',
data: /*JSON.stringify({name: nom})*/{},
//dataType: "json",
success: function (data) {
console.log(data);
}
});
});
On the head I have:
<meta name="csrf-token" content="{{ csrf_token() }}">
I've tried to comment csrf on Kernel.php and when I did it it worked...
I have also added route group to the route:
Route::group(['middleware' => 'web'], function () {
//Form routes
Route::post('ajaxform', 'formulariosController#contacts');
});
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.
I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}
I know this may be a trivial question but I am just not able to get this ajax call to work..
View (html)
<div class="col-sm-6 col-xs-3 pl0" style="margin-left: -5px;">
<button class="btn btn-primary visible-xs" name="btn-callback"><i class="fa fa-arrow-right" aria-hidden="true"></i></button>
<button class="btn btn-primary hidden-xs" name="btnCallback" id="btnCallback"><i class="fa fa-arrow-right" aria-hidden="true"></i> Instant Callback
</button>
</div>
now I am placing a click event on btnCallback button
JQuery code
$('#btnCallback').click(function () {
var phone = document.forms["frm-callback"]["callphone"].value;
if (phone.length != 10) {
document.getElementById('errcallbackModal').innerHTML = "Enter 10 digit Phone number";
return false;
} else if (isNaN(phone)) {
document.getElementById('errcallbackModal').innerHTML = "Please Enter only number";
return false;
} else {
document.getElementById('errcallbackModal').innerHTML = "";
var randomnum = Math.floor(100000 + Math.random() * 900000)
randomnum = randomnum.toString().substring(0, 5);
var fullNumber = '0091' + phone;
url = '/ambulance/type2/sendOtp';
data = {
Code: randomnum,
MobNumber: fullNumber,
};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(fullNumber);
$.ajax({
url: url,
data: data,
type: 'POST',
datatype: 'JSON',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
}
});
</script>
web.php (routes)
Route::post('/ambulance/type2/sendOtp', 'AmbulanceController#sendOtp');
Controller
public function sendOtp()
{
$code = Input::get('Code');
$mobnum = Input::get('MobNumber');
//set otp code in session to verify
// session(['verifyOtp' => $code]);
// ParseCloud::run('sendcode', ["Code" => $code, 'MobNumber' => $mobnum]);
return Response::json(['status' => true, 'message' => 'OTP has been sent to your mobile number']);
}
It's not entering the success callback. There is some trivial mistake with the code but I am not able to figure it out.
Any assistance will be highly appreciated.
I tried the below code and it worked .. hope it helps somebody
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '<?= csrf_token() ?>'
}
});
$.ajax({
url: '/ambulance/type2/sendOtp',
data: {'Code': randomnum, 'MobNumber': fullNumber},
type: 'POST',
datatype: 'JSON',
success: function (response) {
if (response.status === true) {
console.log('success');
} else {
document.getElementById('errcallbackModalOtp').innerHTML = "Some error occured .. Please try again later";
// $('#errcallbackModalOtp').html('Some error occured .. Please try again later');
}
},
error: function (response) {
document.getElementById('errcallbackModalOtp').innerHTML = response.message;
// $('#errcallbackModalOtp').html(response.message);
}
});
try passing the csrf token in the header (this will only work inside a blade.php file)
also might be worth reading this http://engageinteractive.co.uk/blog/csrf-protection-with-ajax-and-laravel
or researching laravel csrf with ajax
$.ajax({
url: url,
headers: { 'csrftoken' : '{{ csrf_token() }}' },
data: JSON.stringify(data),
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
I wanted to just comment, but I can't, so please don't mark my answer as not useful.
You're being redirected and your controller does not give a redirect response. So maybe your route is wrapped into a middleware group redirecting in some cases?
Add contentType & JSON.stringify(). Try code written below.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(fullNumber);
$.ajax({
url: url,
data: JSON.stringify(data),
type: 'POST',
datatype: 'JSON',
contentType: 'application/json',
success: function (response) {
if (response.status === true) {
console.log(response.message);
$('#myModalCallback').modal('toggle');
} else {
alert('Issue');
}
},
error: function (response) {
$('#errormessage').html(response.message);
}
});
I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.