404 (Not Found) file, request using laravel with jQuery Ajax - php

I'm currently working on a migration from native PHP to laravel.
The issue is when I try to make a request through Jquery Ajax:
console.log("Join Save TOken Func");
jQuery.ajax({
type: "POST",
url: "/app/controllers/router.php",
data: { controller: 'api_token', action: action, token: Token, token_name: Token_name, expire_date: Expire_date, permissions: Permissions },
cache: false,
success: function(r) {
...
The console log returns:
POST http://127.0.0.1:8000/app/controllers/router.php 404 (Not Found)
I have this Js file in the directory:
public\assets\js
I had some issues accessing to other paths different to the /public path, and not sure if this problem is related, because my "router" file is located in:
app\controllers\router.php

you can't access the controller manually from file js or blade, you must use routes on folder routes/web.php to access the controller
if you want to access that controller you must declare this on your routes/web.php
use App\Http\Controllers\router;
Route::POST('/router',[router::class,'index']);
//you can replace 'index' with your function name on laravel
and to access that controller with this
http://127.0.0.1:8000/router
in your situation i think you should read this documentation
https://laravel.com/docs/9.x/eloquent-resources
and this
https://laravel.com/docs/9.x/urls#urls-for-named-routes

Related

How to pass a AJAX call on OctoberCMS

Im using OctoberCMS, the user plugin and I want to send data via AJAX to a controller and save the data in the database (in the column of the logged in user).
So I created a new Route in my routes.php
<?php
Route::get('saveHighscore', 'test\Profile\Controllers\HighScore#saveHighscore')
->middleware('web');
And a controller
<?php
namespace Test\Profile\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use October\Rain\Auth\Models\User;
use RainLab\User\Facades\Auth;
class HighScore extends \Illuminate\Routing\Controller
{
function saveHighscore(Request $request) {
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['highscore' => $request]);
}
}
And my jQuery calls
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveHighscore",
type: "POST",
data: highscore
});
But nothing works. If I call /saveHighscore in my browser with dummy data in the controller, it works fine
It should work without any issue.
But I think you are making 2 different requests
In ajax config you specified -> type: "POST" and you are listening for get request
May be you just need to change Route::get -> Route::post
Now it should work expected.
If any doubts please comment.
The AJAX framework only works on the CMS controller or Backend controllers (controllers extending backend/classes/controller). If you're wanting to send data via AJAX without using the built in AJAX framework, then we would have to see more information from your console / network tab of your browser dev tools to see why exactly it's failing.

ajax from framework7 to laravel gives me unauthorized error

I've been trying to send ajax request to my laravel backend from my framework7 frontend using ajax.
$.ajax({
url: 'localhost:8000/server_file/grabtracks',
data: {task: "tracks"},
method: 'get',
async: false,
}).done(function(data) {
grabbedTracks = data;
});
Here is the code on my Laravel 5.4 routes
Route::get('/grabtracks', 'HomeController#grab_track');
And here is from my controller
public function grab_track()
{
$tracks = Track::all('id','title','location','price','track_file','track_img');
return response()->json($tracks);
}
I've disabled the CSRF tokens for the meantime, but i keep getting
Unauthorized error from my request
I'm at a loss, i've tried searching but only angularJS and laravel comes up.
It's probably your Controller has Auth middleware in your constructor remove the middleware and everything should work fine:
So you can remove this instructor or modify it to web auth:
public function __construct()
{
$this->middleware('auth');
}

DELETE and PUT does not recognize even after adjusting all required apache configurations

I have a Laravel app that I recently uploaded on the server.
From this Question I found that I should add these to end of htaccess file (after all laravel configurations) in public directory:
<Limit GET POST PUT DELETE>
Allow from all
</Limit>
But server can not recognize requests that sent via PUT or DELETE methods and shows this error :
501
Not Implemented
The requested method is not implemented by the server.
Apache version is 2.2.31 and operating system is linux.
What is problem and does remain something that I should be add?
Update:
This is a part of my routes related to issue:
Route::group(['prefix' => 'post'], function () {
Route::resource('/category', 'CategoryController');
});
In the other hand I used a $.delete user defined function like this to send DELETE requests:
$.delete = function (url, data, callback, type) {
if ($.isFunction(data)) {
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
dataType: type
});
}
And I used it to delete a category by it's ID:
$.delete('http://mysite.ir/post/category/20'+ , {}, function (res) {
// console.log(res);
}, 'json');
And destroy method that delete selected category:
public function destroy ($id, Request $request)
{
Category::destroy($id);
return ['success' => true, 'msg' => 'category removed.'];
}
It might be something you also need to change in your apache config file?

Laravel route not found but data saved in DB

I am using laravel 5 POST route in an AJAX call, I have defined it as,
Route::post('user/save-draft', ['as' => 'user/save-draft', 'uses' => 'UserController#saveDraft']);
I am also using Route::resource for the same controller above this save-draft route as,
Route::resource('user', 'UserController', ['except' => 'index']);
I am posting a form using AJAX with loading icon, what I am having strange here is that, data get save in the database, but I receive 404 error in the console like,
jquery.js:9664 POST http://www.example.com/user/save-draft 404 (Not Found)
So strange, and loading icon never get disappear which I do in ajax.done function.
While, my AJAX call is something like that,
var postData = {};
postData['frmSaveDraft'] = $frmSaveDraft.serialize();
startAjaxLoading()
$.ajax({
url: "http://www.example.com/user/save-draft",
type: "POST",
data: postData,
success: function (data) {
alert('success')
stopAjaxLoading();
}
});
UPDATE: Sorry, I missed url in AJAX here in above question,
Any thoughts ?
In controller method, I was returning response as,
echo json_encode(array('response' => true)); exit;
which was causing this issue may be exit keyword.
I have returned the response like,
return Response::json(array('response' => true));
which works great.

how to bypass spring security login check in grails

I have controller method, Which returns json data and does not have security check logic.
def getJsonData(){
// return json
}
I am doing ajax request from a php page from another server(cross domain).
$.ajax({
type: "GET",
url: "http://localhost:8080/training/getJsonData",
data: { ListID: '1'},
dataType: "jsonp",
success: function(data) {
alert('Hi'+data);
$("#success").html(data);
}
});
Data is not coming from the server, It only works when the user is logged in to the app server. How to serve these requests without checking for login in grails.
Add IS_AUTHENTICATED_ANONYMOUSLY above your grails action, like
#Secured('IS_AUTHENTICATED_ANONYMOUSLY')
def getJsonData() {
....
}
EDIT...................................................................................
OK then may be you are using url mapping in config file(Simple Map in Config.groovy).
Change there like
grails.plugins.springsecurity.interceptUrlMap = [
...
'/training/getJsonData/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
...
]
That depends on how your application is configured with Spring Security.
If you are using the default configuration:
grails.plugins.springsecurity.securityConfigType = "Annotation"
You can either annotate the method for the action getJsonData with #Secured('IS_AUTHENTICATED_ANONYMOUSLY') or put a configuration in Config.groovy:
grails.plugins.springsecurity.controllerAnnotations.staticRules = [
'/training/getJsonData/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
]
Otherwise, if you are using the InterceptUrlMap:
grails.plugins.springsecurity.securityConfigType = "InterceptUrlMap"
You should configure an entry in your interceptUrlMap like this
grails.plugins.springsecurity.interceptUrlMap = [
'/training/getJsonData/**': ['IS_AUTHENTICATED_ANONYMOUSLY'],
// ...
]
Check out the appropriated section in the Spring Security plugin documentation.
Also, beware of using methods named getFoo in the controllers, they are called when the controller is created -- this is documented in the Gotchas page at Grails wiki. You should probably rename your method to avoid any problems.

Categories