so I have an ajax call to a contoller which is logging me in, I know this is working because of Auth::check($user) and the returned cookie data, such as the laravel session cookie.
However, my problem is in my routes.php, I still can't get to the authorized only pages, and keep hitting the welcome view.
My routes.php:
use App\punsmodel;
use Illuminate\Http\Request;
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken'
]);
if (Auth::guest()) {
Route::get('/', function () {
return view('welcome');
});
} else {
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
return view('mainview');
});
Route::get('mainview', function () {
return view('mainviewMolly');
});
});
}
My controller:
namespace App\Http\Controllers;
use App\Email;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Google_Client;
use Auth;
use App\User;
class verify extends Controller
{
public function verifyIdToken(Request $request)
{
$user = User::where('name', 'Molly')->first();
Auth::login($user);
if (Auth::check($user))
{
return response()->json(['Logged In' => "Yes!"]);
}
}
}
So I do an ajax request to the above controller, which works as I get the json response that says I was logged in, however then when I refresh the homepage, I still get the welcome page not the mainview. Why is this the case?
My ajax request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "http://mysite.come/google",
data: { email: profile.getEmail(),
id: id_token }
}).done(function() {
$("#google").text("You Are Indeed Who I Thought You Were! :)");
}).fail(function() {
$("#google").text("You Are Not Who I Thought You Were, Please Go Away!");
setTimeout(function() {
window.location = "https://en.wikipedia.org/wiki/Special:Random";
//}, 4000);
}, 9999999000);
})
Related
those are my routes and all send me to welcome blade; for example, if I try to go to about. blade it end up in welcome blade
Route::group(['prefix' => '{locale}'],function(){
Route::get('/','Room_randring_welcom#index')->name('post')->middleware('setLocale');
});
Route::get('/about', function () {
return view('aboutUs');
});
Route::get('/rooms', function () {
return view('Room');
});
Route::get('/contact','Email_send#contact');
Route::post('/contact','Email_send#Contact_Submit')->name('Contact.submit');
Route::get('/Gallery', function () {
return view('Gallery');
});
Route::get('/room_detail', function () {
return view('room_details');
});
So my friend and I are working on an admin view for user management. I wanted this view to be able to delete users by clicking a button.
The user list itself looks like this:
#section('main')
#csrf
<ul class="collapsible">
#foreach($users as $user)
<li method="POST" action="delete">
<div class="collapsible-header">
<i class="material-icons">face</i>{{$user->fname}} {{$user->lname}}
</div>
<div class="collapsible-body" id="{{$user->id}}">
<p>Adresse: {{$user->address1}}, {{$user->postalcode}} {{$user->city}}</p>
<p>Land: {{$user->country}}</p>
<p>E-Mail: {{$user->email}}</p>
<span>Beigetreten: {{$user->created_at}}</span>
<br>
<a class="btn red waves-effect waves-light user-delete-button" href=""
id="user-delete-button" data-userid="{{$user->id}}">
<i class="material-icons">delete</i>
</a>
</div>
</li>
#endforeach
</ul>
#endsection
The script in the extended dashboard.blade.php template is the following:
<script>
$(document).ready(function(){
$('.collapsible').collapsible();
$('.user-delete-button').click(function (e){
$.ajax({
url: '{{route('deleteuser')}}',
data: {"userid": $(this).data("userid")},
type: 'post',
success: function(data)
{
console.log('deleted');
}
});
});
});
</script>
The UserController:
class UserController extends Controller
{
public static function destroy($id) {
$user = \App\Models\User::findOrFail($id);
$user->delete();
return redirect('/userlist');
}
//
}
And at last the Route in the web.php:
Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');
So now whenever I am trying to delete a user clicking the button, I get an "500 Internal Server Error" in the console.
At this point I am more than just clueless as to what I am supposed to do to make this work.
The only thing I want is to delete a record and refresh the database by simply clicking a button. But currently nothing I tried worked so far.
I hope you can help me. Thanks in advance!
your must need header file in your request so use this
type:'post',
header
Option 1: Add {id} parameter to your route.
Route::post('/deleteuser/{userid}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
class UserController extends Controller
{
public function destroy($userid) {
$user = User::findOrFail($userid);
$user->delete();
return redirect('/userlist');
}
}
Option 2: Use Route Model Binding in your route and controller action:
Route::post('/deleteuser/{user}', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
class UserController extends Controller
{
public function destroy(User $user) {
$user->delete();
return redirect('/userlist');
}
}
Option 3: Use Request object to retrieve query string
Route::post('/deleteuser', [UserController::class, 'destroy'])->name('deleteuser');
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function destroy(Request $request) {
$user = User::findOrFail($request->query('userid', null));
$user->delete();
return redirect('/userlist');
}
}
Maybe you were getting 500 error because your controller class was not found. You need to use full namespace. Modify your code as follows:
Route:
Route::post('/deleteuser', [App\Http\Controllers\UserController::class, 'destroy'])->name('deleteuser');
Controller:
class UserController extends Controller
{
public static function destroy(Request $Request) {
$id = $Request->input('userid');
$user = \App\Models\User::findOrFail($id);
$user->delete();
return redirect('/userlist');
}
}
N.B: For POST request, you need to send csrf token via your ajax data
data: {
"_token": "{{ csrf_token() }}",
"userid": $(this).data("userid")
}
or you can add header parmas like this way:
$.ajax({
url: '{{route('deleteuser')}}',
data: {"userid": $(this).data("userid")},
type: 'post',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
success: function(data)
{
console.log('deleted');
}
});
Hope this will work!
I am new in laravel I am simply wants to insert form input field data into database using jquery ajax but now problem is that when I click on submit button it show 404 error but when I write localhost/practice/public/save in url then (1/1) MethodNotAllowedHttpException. I don't know whay and where I am doing wrong? Please help me.
app/http/controllers/UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use DB;
class UserController extends Controller
{
public function save(Request $request)
{
$username = $request->input('username');
$password = $request->input('password');
$confirm_id = md5($username);
$data = array(
'username'=>$username,
'password'=>$password,
'confirm_id'=>$confirm_id
);
print_r($data);
}
}
resources/view/index.blade.php
<script>
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
username = $("#email").val();
password = $("#password").val();
$.ajax({
type:"POST",
data:{"username":username,"password":password,"_token":"{{csrf_token()}}"},
url:"{{URL::to('save')}}",
success:function(data){
$("#success").html(data);
}
});
});
});
</script>
route/web.php
<?php
Route::get('/',function(){
return view('index');
});
Route::post('save','UserController#save');
You can't open a post request directly in URL. It will always return MethodNotAllowedHttpException(The GET method is not supported for this route. Supported methods: POST)
So something wrong in ajax request.
url:"{{URL::to('save')}}",
Try to replace this url: {{ url('save') }}
I'm trying to setup a simple POST method with AJAX, posting to a Laravel controller and processed.
The issue I am having is returning a response that the AJAX call understand and can use.
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
AJAX stuff to get form data:
$('#supplierChainCheckForm').submit(function( event ) {
event.preventDefault();
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
// As we're using the "csfrUnsafeMethod" of POST - we'll need to setup the csfr token to be passed between client and server:
$.ajaxSetup({
// This is standard before send method for the ajaxSetup() function:
beforeSend: function(xhr, settings) {
// If settings.type in $.ajax method is unsafe i.e., if it is 'POST' then we'll need to set X-CSRFToken in the xhr Request Header: omitted && sameOrigin(settings.url) currently;
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", $('meta[name="csrf-token"]').attr('content'));
}
}
});
// Get all the form inputs into an array:
var $inputs = $('#supplierChainCheckForm :input');
// We can now loop over all of the input names & values of the form:
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajax({
type: 'POST', //This will always be a post method for the supplier chain check form.
url: 'supply-us/application', //URL endpoint for the post form method: we'll set this to the controller function we're targeting.
data: { 'companyName': values['companyName'] ,'_token': '{{ csrf_token() }}'}
}).done(function(response) {
console.log(response.companyName);
});
});
ApplicationController.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication() {
if (!Input::get('companyName') == null) {
$company = Input::get('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}
However, combining all of the above gives me
console.log(response.companyName) as "undefined"
Please advise. Please note, I am using Laravel 4.1.*
Update function parameter as below;
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (!$request->input('companyName') == null) {
$company = $request->input('companyName');
return Response::json([ 'companyName' => $company ], 200);
} else {
$company = "No compnay specified";
return Response::json([ 'companyName' => $company ], 200);
}
}
}
I think this code has a lot of errors. What i need is to create a form, do a XHR submit to the controller, get the data, send to model, check the validations, return to controller with the output of validation and then sent to the view the message "errors or success"
routes.php
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
<?php
echo Form::open(array('url' => 'checkValidationEmail', 'class' => 'form_notify'));
echo Form::text('Email', Input::old('Email'), array('placeholder'=>'Email', 'class' => 'hg'));
echo Form::close()
?>
Notify Me!
ok, this works fine, next, the problems begin.
AJAX
<script>
$(function () {
$(".send_email").click(function () {
email = $('.hg').val();
$.ajax({
type: "POST",
url: 'checkValidationEmail', //what is the correct url?
data: {
email: email
}
}).done(function (msg) {
alert(msg);
});
});
});
</script>
500 error:
{"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException","message":"","file":"C:\\VertrigoServ\\www\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Router.php","line":1439}}
Controller
class HomeController extends BaseController {
public function checkValidationEmail() {
//how to get the data from form and pass to the model, more exactly validate($input)
if ($validation) {
return true;
}
else {
return 'incorrect email'; //how send this message to the view?
}
}
}
Model
class Home extends Eloquent {
protected $table = 'emails';
public function validate($input) {
//validations
}
}
In your route you are defined the checkValidationEmail as GET request and from your ajax, you are trying to access this as a POST request. So this will throw MethodNotAllowedHttpException. So you have to change your route from,
Route::get('checkValidationEmail', 'HomeController#checkValidationEmail');
To,
Route::post('checkValidationEmail', 'HomeController#checkValidationEmail');
Or,
Route::any('checkValidationEmail', 'HomeController#checkValidationEmail');