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',
]);
});
Related
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 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
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!!!
When I ajax accessed to server, I got 422 (Unprocessable Entity) error.
Does anyone know how to fix it?
<meta name="csrf-token" content="{{ csrf_token() }}" />
<script>
$(document).ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: 'post',
url : 'http://example.com/contact',
data: {_token: CSRF_TOKEN},
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
});
</script>
I got this error.
http://example.com/contact 422 (Unprocessable Entity)
I checked form data by Google Chrome. It seems to be OK..
_token:nBfBpE56cFqgmEy94KCji975dZXt3K5MSnlHJT5y
Update
I added 'address' parameter which was required parameter by following ConvertToInt32's commnet. And then I got another error which was HTTP 403 (Forbidden) error.
<script>
$(document).ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
var address = $("textarea#address").val();
$.ajax({
type: 'post',
url : 'http://example.com/contact',
data: {'_token': CSRF_TOKEN, 'address' : address},
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
});
</script>
Update
app\Http\Requests
<?php namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
abstract class Request extends FormRequest {
public function authorize()
{
// Honeypot
return $this->input('address') == '';
}
}
ContactRequest
?php namespace App\Http\Requests;
class ContactRequest extends Request {
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'message' => 'required'
];
}
}
Request parameter may be OK.
_token:nBfBpE56cFqgmEy9wKCjixf5dZXt3K4MSnlHJT3y
address:a
422 is natural response code in laravel for invalid data when submitting forms via ajax.And your data must include all fields that is defined in your request rules method.
403 means you are not authorized to perform that request.In your request class there is method called authorize().And you can use this method to check if user has an authority to make this request.If this return false then you will get 403 error.
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() );
}