I'm trying to get a simple ajax request working and all I'm getting is 404 errors. I've followed several tutorials to no avail.
the error I'm getting is: POST http://localhost/AjaxReq 404 (Not Found)
my ajax script on is my main.blade.php at the moment for testing
$.ajax({
url: '/AjaxReq',
type: 'POST',
dataType: 'html',
contentType:'application/json',
headers:{'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data:
{
data1: 'ABC',
data2: 'DEF'
},
error: function() {alert('Error');},
success: function(response) {
$('#ajaxResponse').empty();
$('#ajaxResponse').append(response);
}
});
I have this in my web.php
use App\Http\Controllers\AjaxController;
and
Route::post('AjaxReq', [App\Http\Controllers\AjaxController::class, 'ajaxReq'])->name('ajaxReq');
my AjaxController.php is just this for now
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function ajaxReq(Request $request)
{
//
}
}
This is driving me mad, 12 YouTube videos and countless websites and posts on here and every time I get either this error or Controller not found.
Please help.
EDIT: changing to get and going to the page gives a 404, changing the route to your suggestion still 404 and route:list shows POST | AjaxReq | ajaxReq | App\Http\Controllers\AjaxController#ajaxReq | web –
EDIT 2:
ok so i can go to http://localhost/cms/public/AjaxReq with the route get to get and it will run what i put in the controller function but im still getting 404 on the ajax
Related
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
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.
The second problem is with the routing. I've registered correctly a post route in Simple Router but if I call it to post some data using ajax, I will get always this error:
Fatal error: Uncaught Pecee\SimpleRouter\Exceptions\NotFoundHttpException: Route "/event/add/" or method "post" not allowed.
This is how I've registered the routes, I've followed the documentation:
<?php
/* set the namespace for all controllers */
SimpleRouter::setDefaultNamespace('Controllers');
/* this will render the index */
SimpleRouter::get('/', 'Controller#index');
/* this will render the regeistration form */
SimpleRouter::get('/signup', 'Controller#registration');
/* this route is called with ajax and work without problems */
SimpleRouter::post('/user/add', 'UserController#addUser');
/* also this route is called by ajax and works too */
SimpleRouter::post('/user/verify', 'UserController#validateUser');
/* this route will render a form */
SimpleRouter::get('/event/create', 'Controller#eventForm');
/* this is the route that will generate the error message, but will work and send data to the controller */
SimpleRouter::form('/event/add', 'EventsController#addEvent');
/* this route works without problems */
SimpleRouter::get('/search/event/{id}', 'EventsController#searchEvent');
/* Start the routing */
SimpleRouter::start();
?>
JS code:
$('#save-event').on('click', function(e){
e.preventDefault();
var data = $('#event-form').serialize();
$.ajax({
type: 'POST',
url: 'add',
data: data,
cache: false,
beforeSend: function(){},
success: function(response){
console.log(response);
}
});
});
The data passed with ajax to /event/add are saved correctly inside the database, this is strange.
Any help to fix the issue will be appreciated
Your code is posting to the url /event/add/ <- Notice the trailing slash.
You can correct this by changing your code to post to /event/add.
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');
}
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.