Consume Passport fror Ajax calls : Laravel - ajax

I am using Passport within my Laravel-5.7 based application. It is first time for me to work on any Laravel application using Passport. I am able to generate oauth_access_token successfully. However, integrating Passport in my application breaks running ajax calls. I tried to find solution on Internet but I am missing some point.
Whenever, I make a ajax request I get this result {"message":"Unauthenticated."}
Since, this route is supposed to be used in admin panel, it consumes a protected route. Here, is my Javascript code for ajax call:
jQuery(function ($) {
startTime();
$('button[name="controller"], button[name="generateApi"]').on('click', function () {
var url = "";
var button = $(this);
var data = {api_token: "{!! $user->api_token !!}"};
if (button.hasClass('tre')) {
url = "{{ route('abc') }}";
} else {
url = "{{ route('xyz') }}";
data.dataId = button.data('id');
}
var x = document.cookie;
$.ajax({
url: url,
headers: {
"X-CSRF-TOKEN" : '{{ csrf_token() }}',
"Authorization": "Bearer " + "{{ Cookie::get('laravel_token') }}",
},
type: 'post',
dataType: 'json',
data: data,
}).done(function (res) {
if (button.hasClass('tre')) {
$('input[name="apiKey"]').val(res.apiKey);
return true;
}
$(button).toggleClass('btn-success btn-danger');
});
});
});
API route declaration:
Route::post('functionCall', ['middleware' => 'auth:api', 'uses' => 'XYZ#functionCall', 'as' => 'xyz']);
Please, help me sort out what I am missing in this code.

If you're consuming your own API with Javascript, you need to add the middleware Laravel\Passport\Http\Middleware\CreateFreshApiToken::class to your route. See docs: https://laravel.com/docs/5.6/passport#consuming-your-api-with-javascript.

Related

Ajax Call return error like "The POST method is not supported for this route. Supported methods: OPTIONS " in Laravel

I am fetching some data from server using ajax on page loading. But these calls always returns error as The POST method is not supported for this route. Supported methods: OPTIONS. I have tried all the options I can but no use. Here is my code.
var today = new Date();
var monthYear = moment(today).format('MMM/YYYY');
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: baseUrl + 'statisticalboxes',
method: 'POST',
data: {
'project-month': monthYear
},
success: function(data) {
console.log(data);
},
error:function(e) {
console.log(e);
}
});
web.php
Route::post('statisticalboxes', ['as' => 'statisticalboxes','uses' => 'DashboardController#getStasticalBoxData']);
I have changed method into all other options, but no use.
When I look into the network tab, the requested url look like
Request URL: http://127.0.0.1:8000/nullstatisticalboxes, but the actual one is Request URL: http://127.0.0.1:8000/statisticalboxes
Your baseUrl variable return null value.
Where you define baseUrl?
Define baseUrl variable.
--- OR ---
Use url like this.
url: '/statisticalboxes',

AJAX POST Request in Laravel says url not found

I am trying to post data to a controller through ajax request. But it can't find the route and says the following in console.
POST http://127.0.0.1:8000/addNotification_action 404 (Not Found)
This is my ajax call below.
function editNotification(obj) {
// alert(obj.id);
var obj_id = obj.id;
var id = obj_id.split("_");
$.ajax({
url: "{{ url('addNotification_action') }}",
type: 'POST',
dataType: 'json',
data: {edit_notification_id: id[1]},
})
.done(function(result) {
console.log(result);
$('#title').val(result['title']);
$('#description_notification').val(result['details']);
$('#edit_flag_notification').val(result['notification_id']);
})
.fail(function() {
alert("error");
});
}
And I am just trying to dd() the request I get in the controller. Please help. Thanks
First of all, you should create a route and give this route a name. You have to generate the ajax url as "route('route_name')".
// Route (for Laravel 8)
Route::post('addNotification_action', [NotificationController::class, 'notify_method'])->name('notify');
// Ajax Settings
....
url: "{{ route('notify') }}",
....
Jus Give admin/addNotification_action in Ajax URL

Laravel Ajax can't pass parameter in url but works with a constant

I'm writing an ajax that works when url contains a constant but does not work when url contains a variable because this does not get replaced by the actual value.
$('body').on('click', '.deleteLayer', function () {
var layer_id = $(this).data('id');
confirm("Are You sure want to delete record with layer_id="+layer_id+"?");
$.ajax({
type: "POST",
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
data: {_method: 'delete', layer:layer_id},
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
If I use a value, let's say 50 instead of layer_id then it works!!!:
url: "{{ route('layers.destroy',['layer' => 50])}}",
This is the route that I try to access:
DELETE | admin/layers/{layer} | layers.destroy
If I do not send layer parameter in the url I receive the following error
message : "Missing required parameters for [Route: layers.destroy]
[URI: admin/layers/{layer}]. (View:
/var/www/laravelapp/resources/views/layers.blade.php)"
Why is layer_id, here
url: "{{ route('layers.destroy',['layer' => "+layer_id+"])}}",
not replaced by the actual value?
When you are writing like ['layer' => "+layer_id+"] the js variable is not working. It goes like +layer_id+ as the parameter of the route. You can try like this
var layer_id = $(this).data('id');
var url = '{{ route("layers.destroy", ":id") }}';
url = url.replace(':id', layer_id );
$.ajax({
type: "POST",
url: url,
data: {},
success: function (data) {
},
error: function (data) {
}
});
{{URL::to('/destroy')}}+'/'+layer_id;
Route
Route::get('/destroy/{id}', 'controller#destroy')
Controller
public function destroy($id){
// use $id here
}
Hope you understand.

Laravel ajax URL issue

I'm new to Laravel and using Ajax for some functionalities.
//Route
Route::post('some/thing/','Controller#Method');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
//controller
public function Method(Request $object){
if(isset($_POST['val1'])){//do something}
}
problem is in the URL parameter of AJAX. When I'm giving value to the url i.e some/thing/, it gives me 404 error showing www.siteurl/some/thing/some/thing/ not found and when I'm keeping url value blank then it's working. But then i don't think it's a good practice to do like this.
I have seperate .js file in public folder.
Controller in different and blade file in different directory. Laravel version 5.6.22
thank you.
I think you have to change the Url to the absolute path:
Incase you are working on Blade file:
Change the url from : url: "some/thing/",
To url: {{url('some/thing')}},
In case you are working on external Js File:
Change the url from : url: "some/thing/",
To url: url: "/some/thing/",
When you write the url to ajax its trying to achieve some/thing/some/thing/
To fix; give a name for your route and then use this name for your ajax url.
//Route
Route::post('some/thing/','Controller#Method')->name('yourRouteName');
//jQuery
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "{{ route('yourRouteName') }}",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Use absolute path instead of relative. append / before the url like "/some/thing/"
$('.some_class').click(function(){
var var1 = $('.some').val();
var val2 = $(".another").val();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
//this part
url: "/some/thing/",
type:"POST",
data: { var1: var1,val2: val2,_token: CSRF_TOKEN},
success:function(response){
console.log("working");
},
error:function(){
console.log("error");
}
});
});
Hope this helps.
You can add route in $except array in VerifyCsrfToken middle ware to ignore csrf token verification on that route
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
"/some/thing/"
];
}

Laravel 5 Ajax Post route

This is my first attempt to use ajax to Post instead of Get. I get a 200 response as if it were working but the function in the controller is never being run.
I used this same concept in my ajax Get requests and they work fine but the Post is not working as expected and sortable('serialize') creates a Post variable so I need to use Post.
The alert in the success: function always runs as if it were successful but the controller function is never hit (I have it making a simple database change just to verify if it is running).
Ajax:
$(function() {
$('[id^="sortable_"]').sortable(
{
connectWith: '.sortable-line-item-list-5',
update : function (event, ui)
{
var items = $(this).sortable('serialize');
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
},
success: function()
{
alert('looks like it is working...');
},
});
}
});
$( '[id^="sortable_"]' ).disableSelection();
});
Route:
Route::post('api/sort_order_item', ['as' => 'api/sort_order_item', 'uses' =>'ApiController#SortOrderItem']);
Controller:
public function SortOrderItem()
{
$this_item = \pmms\Checklist_template_line_item::findOrFail(20);
$this_item->list_position = 1;
$this_item->save();
}
I think your problem is csrf_token,
Put this line in your blade page head section:
<meta name="csrf-token" content="{{ csrf_token() }}" />
then, update your ajax code like this :
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
success: function()
{
alert('looks like it is working...');
},
});
Let me know if it helps you

Resources