Method on redirect()-to() - php

I'm new in Laravel!!
I have a js that send a request DELETE to my controller:
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
Than my controller return redirect
public function destroy(User $user)
{
$this->repository->delete($user->id);
return redirect()->to(route('users.index'));
}
This route "users.index" has the "GET" method, but the redirect is considering the DELETE method, resulting in this error:
DELETE http://localhost:8000/users 405 (Method Not Allowed)
Can i change the method using in redirect?
Tks!

Ajax request will always follow redirects (actually, there's a work around), so you probably should change your controller to avoid redirects if this is an ajax request.
use Illuminate\Http\Request;
# [...]
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
if ($request->ajax()) {
return $user;
}
return redirect()->to(route('users.index'));
}
If this controller only receives ajax requests, you can make it simpler.
public function destroy(Request $request, User $user)
{
$this->repository->delete($user->id);
# or return whatever you want with: response()->json($contents);
return $user;
}
[UPDATED] Making redirects after ajax
As #PatricQ mentioned, you might want to make the redirect after the ajax call. If this is the case, I suggest that you create a response format that your javascript understands and makes a redirect.
An example would be to return the redirect URL:
return response()->json(['redirect' => true, 'to' => route('users.index')]);
This way, in your javascript you would check for the redirect flag.
$.ajax({
url: link,
method: 'DELETE',
data: {
_token: $('input#_token').val(),
},
success: function (response) {
if (response.redirect) {
window.location.href = response.to;
}
},
});

Related

Ajax GET request is empty despite correct query string parameter

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}

Form AJAX post response cycle in Laravel 4.1.*

I have a rather old site that I have inherited as part of a new position - it's been built to Laravel 4.1.* version specs.
My issue is Response::json returning undefined variables in the response, using standard AJAX post method with all CSRF stuff and ajaxSetup() defined correctly.
application.blade.php
$.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'] }, //This will carry the form data that is needed to be passed to the server.
success: function (response) {
console.log(response['companyName']); << THIS LINE RETURNS "undefined"
console.log(typeof response) << THIS LINE RETURNS string
},
error: function (response) {
console.log(response);
},
});
values['companyName'] returns what I input into the form. The above "response" simple chucks back html - so I think my routes might be incorrectly defined or incorrectly defined in the AJAX url param, perhaps? Here are the two applicable routes:
routes.php
Route::controller('supply-us/application', 'ApplicationController');
Route::post('supply-us/application', 'ApplicationController#processSupplierApplication');
ApplicationController.php:
<?php
use Illuminate\Http\Request;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $request) {
if (Input::has('companyName')) {
$this->companyName = Input::get('companyName');
$data = [
'success': true,
'companyName': $this->companyName
];
return response()->json($data);
}
}
}
Any pro-tips would be greatly appreciated!
to check what your are missing in controller when posting or getting your result
usually which i follow
in blade.php
<.form method="post" action="{{url('supply-us/application')}}".>
{{csrf_field()}}
<.input type="text" name="companyName".>
<./form.>
remove dot try this it will help you to find missing thing in controller
in your blade
<.input type="text" name="companyName" id="companyName".>
in your ajax
var company = $('#companyName').val();
$.ajax({
type: 'POST',
url: 'supply-us/application',
data: { 'Company':company,'_token': '{{ csrf_token() }}' },
success: function (response) {
alert(data) // if this not work then try this alert(data.company)
},
error: function (response) {
console.log(response);
},
});
in your controller
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
class ApplicationController extends FrontController {
public function getSupplierApplication() {
return self::getPage('supply-us/application');
}
public function processSupplierApplication(Request $req) {
if (!$req->get('Company')==null) {
$company = $req->get('Company');
return response()->json($company);
}else{
$company="no input give";
return response()->json($company);
}
}
}

Laravel How to delete session on the homepage

Im using javascript in Homepage to pass variable to next page (Im using controller to store variable in session) , now how can I empty the session if loaded the home page again?
$(document).on('click', '.btn_getbids', function() {
$.ajax({
type: 'post',
url: 'addItem',
data: {
'_token': $('input[country=_token]').val(),
'country': $('input[name=country]').val() },
success: function(data) {
}, });
$('#country').val('');});
Controller
public function addItem(Request $request) {
$request->session()->put('country', $request->country);
return response ()->json ( $data );
}
Assuming you have an IndexController where you call the homepage function to call your home view.
public function homepage(Request $request){
//check if session exists
if($request->session()->has('country'){
//forget session
$request->session()->forget('country');
}
}
With this code, session country will be forgotten every time you go to the homepage.
For your additional reference Laravel Sessions
Have you tried:
public function addItem(Request $request) {
if($request->session()->has('country'){
$request->session()->forget('country'); //if you want to clear specific one
//$request->session()->flush //if you want to flush all
}
$request->session()->put('country', $request->country);
return response ()->json ( $data );
}

Cakephp 3.4 AJAX request throws 403 forbidden error

I have been trying to send some data to a controller via AJAX but for the life of me I can`t seem to make it work; everytime I make the request, a 403 forbidden error is thrown.
this is the ajax request:
$.ajax({
type: 'post',
url:"<?php echo Router::url(array('controller'=>'Atls','action'=>'saveTime', '_ext' => 'json'));?>",
dataType: 'json',
data: {atl_id: idTimerPaused, time: actual_time},
beforeSend: function(xhr){
},
success: function (response) {
console.log('Nailed It');
},
error: function(jqXHR, exception){
console.log(jqXHR);
}
});
return false;
the controller action:
public function saveTime()
{
if ($this->request->is('post') && $this->request->is('ajax')) {
$content = $this->request->getData();
$query = $this->Atls->query();
$result = $query
->update()
->set(
$query->newExpr('actual_time = '. $content['time'])
)
->where([
'id' => $content['atl_id']
])
->execute();
$this->set(compact('content'));
$this->set('_serialize', ['content']);
$this->render('ajax_response', 'ajax');
}
}
I have loaded the extensions on the routes.php file (Router::extensions('json', 'xml');)
The request handler is also loaded and the function is allowed:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('saveTime');
//Change layout for Ajax requests
$this->viewBuilder()->layout('appTemplate');
if ($this->request->is('ajax')) {
$this->viewBuilder()->layout('ajax');
}
}
that "ajax_response" view has also been added.
I can't see where the problem could be. So any help I can get to work this out would be much appreciated.
Did you use the 'Csrf'-Component? In my case this was the problem.
https://book.cakephp.org/3.0/en/controllers/components/csrf.html#csrf-protection-and-ajax-requests
When you got an 403 forbidden error in most cases the session is expired and the user has to login again.

ajax post and redirect to new page not work

I use resource make crud, and in the create page, I have to add a preview page
I tried to use ajax post data to admin/article/previewform then in route action controller method previewform catch data and store in variable with redirect to new page preview show it ...
I have problem
1. Why it doesn't redirect to new page ?
2. Why in js console.log get Faild to load resource … statu?s of 500
3. I also try return Redirect::to('admin/article/previewshow'); in previewform then still not redirect to.
But get js console.log with template show.blade.phpthat is in resource show method call.. ??
How to solve it?
js
$.ajax({
url: 'previewform',
type: 'POST',
data: {data: data},
})
.done(function(response) {
console.log(response);
});
route
//.. prefix=>admin
Route::resource('article','AdminArticleController');
Route::post('admin/article/previewform', 'AdminArticlePreviewController#previewform');
Route::get('admin/article/preview', 'AdminArticlePreviewController#preview');
AdminArticlePreviewController
class AdminArticlePreviewController extends AdminController
{
public function preview()
{
$input = Input::get('data');
return Redirect::route('admin/article/previewshow');
}
public function previewshow()
{
// return View::make('admin.article.preview')->with('data', $data)
}
}
It is not possible to make redirection in this way. For ajax requests you need to catch "redirection command" from the server side script (PHP) and execute it in the JS.
Instead:
return Redirect::route('admin/article/previewshow');
you can use:
return Response::make('/redirect/url', 301)
then JS code:
.done(function(response) {
console.log(response);
});
can be replaced by something like:
.done(function(data, statusText, xhr) {
if(xhr.status == 301) {
window.location = data;
}
});

Categories