I tried this code:
Angular JS:
$http({
method:"POST",
url:baseurl+'/login',
data:info
});
routes.php
Route::get('/login', 'LoginController#doLogin');
LoginController.php
public function doLogin()
{
return json_encode( Input::all() );
}
Related
I am sending the axios request to laravel login controller.
Axios code
attemptLogin()
{
axios.post('/login',
{email:this.email, password:this.password, remember_me:this.remember_me},
{ headers: {
'Content-type': 'application/x-www-form-urlencoded',
},
}).then((resp) => {
console.log(resp);
// location.reload();
}).catch(error => {
this.errorMessage = error.message;
console.error("There was an error!", error);
})
}
Login Controller code
protected function authenticated(Request $request, $user)
{
// return "Login successfull";
return view('home');
}
I don't what's happening, no error is displaying the console.
Is the browser showing anything? From what you have pointed out, you should ensure that the request is hitting the login function in the LoginController. You must be hitting that trait class and then your request is processed.
class LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Actually am answering this my self because I find the exact problem,
Am doing mistake in axios syntax,
correct syntax is below
attemptLogin()
{
axios.post('/login', {
email:this.email, password:this.password, remember_me:this.remember_me
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
}
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>
I'm trying to post ajax in laravel 5, but when i have the function in the controller it works fine but when i try to link to controller, it return error 500 (Internal Server Error)
my JS
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
$.ajax({
url: 'myLink',
type: "post",
data: {
'start': start.format('YYYY-MM-DD'),
'end': end.format('YYYY-MM-DD')
},
success: function(data){
alert(data);
},
error: function(){
alert("error!!!!");
}
});
My route (non working)
Route::post('/admin/getStoreIncome', 'Admin#method');
My route (working)
Route::post('/admin/getStoreIncome', function()
{
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
});
My Controller
public function method() {
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
Namespace i use for my controller
namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
Am i doing something wrong here? Do i need a session namespace for the csrf? If someone have experience with this please help.
I'm not sure my answer will help you, But Through Jquery I have Done
I have a DropDown OnChange I am sending selected Value in My Controller and Then I am getting the response on my view Page
(function($) {
$('#bath').on('change', function() {
var optionSelected = $(this).find("option:selected");
var prop_type = optionSelected.val();
$.ajax({
type: "GET",
url: "baths", //my Controller Function
dataType: "json",
data: {baths: prop_type},
success:function(row)
{
$('#getRequestdata').empty('clear').html(row.html);
}
});
});
})(jQuery);
I hope it will help you!!!
I have a select box. And i'm redirecting clients via select box. When they select they are redirecting.
Before i started to write code with laravel my system was working. After laravel i have a problem with this matter.
$('#parent_products').change(function(){
productid = $(this).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '{{ route('redirectVariant') }}',
data: {
productid : productid,
_method : 'PATCH'
},
error: function(jqXHR, exception) {
alert('Hata \n' + jqXHR.responseText);
},
success: function (data) {
window.location.replace(data);
}
});
});
I'm getting this error.
MethodNotAllowedHttpException in RouteCollection.php line 219:
This is my route
Route::group(['prefix' => 'ajax'], function () {
Route::post('product/redirect_variant', [
'uses' =>'AjaxController#redirectVariant',
'as' => 'redirectVariant',
]);
});
Here is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller
{
public function redirectVariant(Request $request){
dd(Request::all());
}
}
What is the problem ?
Your Javascript is spoofing a PATCH request, while your route is setup for POST.
You could try:
Route::group(['prefix' => 'ajax'], function () {
Route::patch('product/redirect_variant', [
'uses' =>'AjaxController#redirectVariant',
'as' => 'redirectVariant',
]);
});
Controller:
/**
* #Route("/email/{name}/{email}/{subject}/{message}", name="email")
* #Method({"GET", "POST"})
*/
public function indexAction($name, $email, $subject, $message, Request $request){
var_dump($name, $email, $subject, $message);
die;
}
Ajax:
<script type="text/javascript">
$(document).ready(function() {
$('#contact-form').submit(function(event) {
$.ajax({
type:'POST',
url:'./email',
data:"/"+$('#name').val()+"/"+$('#email').val()+"/"+$('#subject').val()+"/"+$('#message').val(),
success:function(response){
alert(response)
}
});
event.preventDefault();
});
});
</script>
I am trying to submit ajax request to the controller. Unfortunately i get 404, and the following error:
No route found for "POST /email" (from "http://localhost/Portfolio/web/app_dev.php/")
PS. The code in the controller is for debuging purposes
You should change your controller to accept only POST request and so you don't need to pass your arguments in the path :
/**
* #Route("/email, name="email")
* #Method({"POST"})
*/
public function indexAction(Request $request){
//your code here
}
To access your post parameters in the controller, use $name = $request->request->get('name'); or consider using Symfony Forms
You also need to change your ajax call to send an object in data:
<script type="text/javascript">
$(document).ready(function() {
$('#contact-form').submit(function(event) {
$.ajax({
type:'POST',
url:'/email',
data: {
name: $('#name').val(),
subject: $('#subject').val(),
email: $('#email').val(),
message: $('#message').val()
},
success:function(response){
alert(response)
}
});
event.preventDefault();
});
});
</script>
This will properly send a POST request to /email
the route /email/{name}/{email}/{subject}/{message} means that you need to send the Request to an URL like this
/email/testName/example#gmail.com/TestSUbject/Testmessage
if you need the /email route to work just change the #Route annotation to /email
and in controller
$request->request->get('email');
//retrieve other fields
...
..
to access the values of the POST request
Also you can also use Symfony Forms to take the Advantages they offer like validation , CSRF Protection , etc