recover AJAX post data with Laravel 5.5 - ajax

I have an Ajax script and i have to recover the datas in a controller as POST and we have error 404 ...
Here is my JS :
function ajax() {
var values = {
'str': "Salut",
'id': "Dave & Alex",
};
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/ajax',
type: 'post',
dataType: 'json',
async: true,
data:values,
success: function (result) {
console.log(result);
},
error: function (result) {
console.log(result);
},
complete: function (result) {
console.log("complete");
}
});
};
Here are my route which is /admin/ajax and which is available to logged in admins:
Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware'=>'admin'], function(){
Route::post('/ajax', 'AdminsController#majax');
});
});
In my Controller i created a method :
public function index(Request $request)
{
if($request->ajax()){
return response()->json(['status'=>'Ajax request']);
}
return response()->json(['status'=>'Http request']);
}
I have 2 issues :
1. I have an Http request displayed as result
2. How can i display the values of my "values" array ?
Thanks for your help

Related

Ajax call Laravel

I am attempting to call my controller that would update my product:
public function update(Request $request, $product_id)
{
$product = Product::find($product_id);
$product->name = $request->name;
$product->test = $request->session()->get('test');;
$product->save();
return response()->json($product);
}
I would like to trigger the event with ajax, a button is clicked and my controller is called with the data that then inserts it into database.
I tried to do:
$.ajax({
type: POST,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
But that already posts before calling my controller, how can i just throw all data to controller instead of posting it?

Trying to get the ajax form submitted data in controller in laravel

I am Trying to get the ajax form submitted data in the controller in laravel but getting nothing in controller request with the following code
ajax
$('.ace_text-input').keyup(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/forksnippet/saveforksnippets',
type: 'POST',
data: $(this).serialize(),
beforeSend: function(result) {
$(".saveforksnippetbutton").attr("disabled", true);
$(".saveforksnippetbutton ").html('Auto saving...');
},
success: function(result) {
$(".saveforksnippetbutton ").html('Auto Saved');
}
});
});
Controller function
public static function saveforksnippets(Request $request)
{
return $request->post('snippet_title');
}
Please help
Add a key to your data object
$.ajax({
url: '/forksnippet/saveforksnippets',
type: 'POST',
data: {
payload: $(this).serialize(),
},
beforeSend: function(result) {
$(".saveforksnippetbutton").attr("disabled", true);
$(".saveforksnippetbutton ").html('Auto saving...');
},
success: function(result) {
$(".saveforksnippetbutton ").html('Auto Saved');
}
});
Parse the serialized data in the controller
public function saveforksnippets(Request $request)
{
parse_str($request->payload, $output);
return $output['snippet_title'];
}
PS: I have removed the static scope of the function.

Laravel ajax form call jQuery function

I'm starting to learn Laravel, first time and first project.
I have my custom login form working, but want to improve it, ajax request works fine, but can't call a JS function. The documentation of the template I'm using says to trigger with JS.
I've tried calling the function directly:
error: function() { // What to do if we fail
One.helpers('notify', {type: 'danger', icon: 'fa fa-times mr-1', message: 'Your message!'});
}
Also tried to call with jQuery.trigger:
error: function() { // What to do if we fail
jQuery.trigger(One.helpers('notify', {type: 'danger', icon: 'fa fa-times mr-1', message: 'Your message!'}););
}
Nothing seems to work.
Ajax Function:
<script type="text/javascript">
/**
* #return {boolean}
*/
function LoginUser()
{
var formData = {
username: $("input[name=login-username]").val(),
password: $("input[name=login-password]").val()
};
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: "/login",
data: formData,
cache: false,
success: function(){ // What to do if we succeed
},
error: function() { // What to do if we fail
}
});
return false;
}
</script>
What I expected is a notification message like this:
What I get:
Absolutely nothing, nothing shows up on the page.
Laravel Routes:
Route::get('/', function () {
if (Auth::check()) {
return Redirect::to('dashboard');
}
return view('auth.login');
});
Route::match(['get', 'post'], '/dashboard', function () {
return view('dashboard');
});
Route::group(['middleware' => 'App\Http\Middleware\LoginMiddleware'], function () {
Route::match(['get', 'post'], '/dashboard/', 'HomeController#dashboard');
Route::match(['get', 'post'], '/admin/users', 'HomeController#admin_users');
Route::match(['get', 'post'], '/admin/permissions', 'HomeController#admin_permissions');
});
Auth::routes();
Route::post('/login', 'Auth\AuthController#postLogin');
Route::get('/logout', 'Auth\AuthController#getLogout');
make sure you didn't miss the csrf meta tag in html head:
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
....
</head>
or you can simply replace the {{ csrf_token() }} with $('meta[name="csrf-token"]').attr('content') in your code, like this:
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
// ...
});
U get this error, because route "login" cant accept "POST" request.
try change type: "post", to type: "get",, u should get something like this:
<script type="text/javascript">
/**
* #return {boolean}
*/
function LoginUser()
{
var formData = {
username: $("input[name=login-username]").val(),
password: $("input[name=login-password]").val()
};
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "get",
url: "/login",
data: formData,
cache: false,
success: function(){ // What to do if we succeed
},
error: function() { // What to do if we fail
}
});
return false;
}
</script>

Ajax calling Area Controller

I am trying to call a Controller from Ajax, but I'm getting:
Failed to load resource: the server responded with a status of 404 ()
The Ajax is calling from the Admin View to the Admin Controller. I can view the Admin Page, but I'm unable to call GetAll() and GetAllUsers() from Ajax or any other method.
In Startup
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute",template:"{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
In AdminController
namespace Project.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
public AdminController()
{
}
[HttpGet("GetAll/{page}")]
public IActionResult GetAll(int? page)
{
}
[HttpGet("GetAllUsers/{page}")]
public IActionResult GetAllUsers(int? page)
{
}
}
}
Ajax:
#section Scripts{
#await Html.PartialAsync("_ValidationScriptsPartial")
<script>
$(function () {
$.ajax({
type: "GET",
url: "/Admin/GetAll",
traditional: true,
success: function (view) {
$("Result").html(view)
}
});
$.ajax({
type: "GET",
url: "/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});
});
</script>
}
in the url you need to user /{areaName}/{controllerName}/{ActionMethod}
$.ajax({
type: "GET",
url: "/Admin/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});

Alert not appearing if i put the route under auth middleware group

I am not allowing the user to submit the form if not logged in. So, giving the alert to login.
Jquery and Ajax
$(document).on('submit', '.bet', function (e)
{
e.preventDefault();
var frm = $(this);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
dataType: 'json',
success: function (data)
{
if(data == 'notloggedin')
{
alert('You must login first!');
}
else if(data==true)
{
swal('Bet Success! The details has been sent to your email!');
}
else if(data=='dateexpired')
{
swal('The match bet time expired!');
}
}
});
});
Controller:
public function store(Request $request)
{
if($request->ajax())
{
if(!Auth::check())
{
echo json_encode('notloggedin');die;
}
....
This went all good. But, if I put this route under auth middleware the alert is not appearing. And in the developer's tool i see unauthorized action. Yes. it is obvious but i still want the alert to appear.
Route::group(['middleware' => ['auth']], function () {
Route::post('/bet/store','BetController#store');
});
The Error is not shown because if the auth middleware fails the response indicates that the request was not successful ( so success method gets not executed ). In this case you have to use .fail() method.
var jqXHR = $.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
dataType: 'json',
success: function (data)
{
if(data == 'notloggedin')
{
alert('You must login first!');
}
else if(data==true)
{
swal('Bet Success! The details has been sent to your email!');
}
else if(data=='dateexpired')
{
swal('The match bet time expired!');
}
}
});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {
if(jqXHR.status == 401) {
alert('unauthorized');
}
});
that's because request is returned (401) from the middleware and controller action is never executed. also middleware is right place for this check why don't you return unauthorised response from auth middleware ? something like this
App\Http\Middleware\Auth
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response()->json(['notloggedin']);
}
return redirect()->guest('login')->withErrors(['You must login first.']);
}
return $next($request);
}
please note that this will return a status 200 for ajax request but I see you are using success function so it would work. You can also return a 401 with
if ($request->ajax()) {
return response('Unauthorized.', 401);
}
and use error method on jQuery

Resources