Laravel Ajax POST Request does not work: 302 found - javascript

I'm trying to push some data via ajax in Laravel. Unfortunally it does not work. When I was watching at the network traffic, i found this:
Request Method:POST
Status Code:302 Found
I'm trying to get data from a JSGrid, which works fine. The data-object is filled. I checked it. For testing I just returned a short message in my controller. But it's not even called when I send the POST request...
Here is my code
Javascript:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
$('#save_list').click(function (e) {
e.preventDefault();
var url = '{{ route("account.save_accounts_to_user") }}';
var post = {};
post.account_list = $("#jsGrid").jsGrid("option", "data");
$.ajax({
type: "POST",
url: url,
dataType: 'JSON',
data: post,
cache: false,
success: function (data, textStatus, jqXHR) {
console.log(textStatus + " - " + data);
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText + textStatus + " - " + errorThrown);
}
});
return false;
});
Route:
Route::post('save_accounts_to_user', ['as' => 'account.save_accounts_to_user', 'uses' => 'AccountController#saveAccountsToUser']); //ajax request
Controller:
/**
* Save all used accounts for a user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function saveAccountsToUser(Request $request)
{
$response = array();
$response["status"] = "ok";
$response["message"] = trans('account.accounts_saved');
return \Response::json($response);
}
I was expecting that I will get the JSON text from the controller method as the responsemessage. But instead i get redirected without calling the wanted method.
I don't know what happens there. There is no middleware assigned to this route, which could be the reason for this redirect.
Do you have an ideas?

After all it was a middleware of an outter group which was redirecting the request -.-

May be 'X-CSRF-Token' used by you instead of 'X-CSRF-TOKEN' mentioned in Laravel docs is the issue here? Try to follow the Laravel docs completely.Please refer below link.
https://laravel.com/docs/5.3/csrf
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

add this code:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
after this:
var url = '{{ route("account.save_accounts_to_user") }}';

Use headers in AJAX call
Example:
$.ajax({
type: "POST",
url: link, // your link
data: DataObject, // data to pass
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (result) {
}
});

Related

Ajax call does not redirect based on Redirect 302 of webapi

I have a c# webapi application where the endpoint just redirects, however, when I call from an HTML page that has an AJAX call, it does not redirect, could you please help me where I'm missing? I tried all combinations.
[HttpPost]
[Route("Redirect")]
public async Task<IActionResult> Redirect()
{
var response = "https://google.com";
return Redirect(response);
}
AJAX call
$.ajax({
url: "https://10.10.45.2/api/Redirect",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, xhr) {
window.location = xhr.location; // I know this is not correct
},
complete: function(xhr, textStatus) {
console.log("Complete: " + xhr.status);
},
error: function (jqXHR, timeout, message) {
console.log("Complete: " + jqXHR.status);
console.log("Response Location :" + loginPageRedirectHeader);
}
});
In short, when ajax sends a request, the data you get should be the json type you agreed on. Redirect will not send matching data back, so your code is wrong and cannot achieve this requirement.
Ajax is used to send http requests, and the sending method and receiving format need to be defined by themselves. In your scenario, it is recommended to use window.location to jump after receiving data in text or json format.
The correct ways for you.
Use <a></a> tag navigate to new page.
Navigate to Google
[HttpPost]
[Route("Redirect")]
public async Task<IActionResult> Redirect()
{
var response = "https://google.com";
return Redirect(response);
}
Get google url from controller.
[HttpPost]
[Route("Redirect")]
public string Redirect()
{
var response = "https://google.com";
return response;
}
$.ajax({
url: "https://10.10.45.2/api/Redirect",
type: "POST",
dataType: "text",
success: function(data) {
window.location = data;
},
error: function (jqXHR, timeout, message) {
}
});

405 Method Not Allowed for POST and PUT in laravel application

I'm trying to drop and resize an event in fullcalendar in laravel, but when I move the event, I have 405 Method Not Allowed error message!..
My web.php file:
Route::get('calendar', 'FullCalendarController#index');
Route::get('/load-events', 'EventController#loadEvents')->name('routeLoadEvents');
Route::put('/events-update', 'EventController#update')->name('routeEventUpdate');
My blade.php file:
<div id='calendar'
data-route-load-events="{{route('routeLoadEvents')}}"
data-route-events-update="{{route('routeEventUpdate')}}"></div>
My .js file:
$(function (){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
function sendEvent(route, data_){
$.ajax({
url: route,
data: data_,
method: 'POST',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
}
function routeEvents(route){
return document.getElementById('calendar').dataset[route];
}
eventDrop: function(element){
let start = moment( element.event.start ).format("YYYY-MM-DD HH:mm:ss");
let end = moment( element.event.end ).format("YYYY-MM-DD HH:mm:ss");
let newEvent = {
_method: 'PUT',
id: element.event.id,
start: start,
end: end
};
sendEvent(routeEvents('routeEventUpdate'), newEvent);
},
So there are really only two types of request that Laravel really understands:
POST & GET
A PUT request is a POST request with a method of PUT.
What laravel is looking for is a _method parameter in the request telling it what type of request this is. in your case _method: PUT.
Try this:
$.ajax({
url: route,
data: data_,
method: 'PUT',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
You put your "put" method in your payload-data, this wont be recocnized by the AJAX Function. Try adding the method as an Argument
function sendEvent(route, data_, sendMethod){
...
method: sendMethod,
...
And call i via
sendEvent(routeEvents('routeEventUpdate'), newEvent, 'PUT');

How to handle X-CSRF-Token for jQuery POST in UI5?

I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.

Converting javascript function into $http provider in Angular

I have the following function below which I am trying to re-write using $http provider. The documentation shows so many different ways of doing this and I cant get it right. Here is the function:
function Ingest(Filename, ID, baseUrl, logger){
var url = baseUrl + '/php/' + 'Ingest.php';
var dataString = 'Filename=' + encodeURIComponent(Filename) + '&ID=' + encodeURIComponent(ID);
$.ajax({
type: "POST",
url: url,
async: true,
cache: false,
data: dataString,
success: function(results){
logger.success('Ingestion process has been finished.', '', 'Success');
}
//fail
, error: function (jqXHR, textStatus, errorThrown){
alert("error:\r\n" + errorThrown);
}
});
}
and here is a sample of $http code:
$http({
method: 'POST',
url: config.appBaseUrl + '/php/' + 'Ingest.php',
data: { ID: encodeURIComponent(ID), Filename: encodeURIComponent(Filename) }
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Thank you
In the 1st sample you do a post, in the second a get.
You can just use shortcut method provided by $http.
$http.post( config.appBaseUrl + '/php/' + 'Ingest.php', Filename: encodeURIComponent(Filename), ID: encodeURIComponent(ID)).then(function(response){
}, function(rejection){
});
If you want to set some specific configuration for the $http (headers,...) use the 3rd argument of the functions.
Note that shortcut post/put have a second argument for request body, 3rd for configurations.Delete and get does not have request body argument so configuration are the 2nd argument of the function.

Update (PUT) a JSON object with ajax - PrestaShop

I am trying to update a JSON object (e.g: customer). But, I have the following error:
"NetworkError: 405 Method Not Allowed - http://prestashop/api/..."
This is my code (index.js):
var testWebService = angular.module('testWebService', []);
testWebService.controller('testWebServiceCtrl', function ($scope, $http) {
var $baseDir = "http://prestashop/api";
var $objectDir = "customers";
var $idObjectDir = "1";
var $keyDir = "F517VWPRREG7TA25DEY8UIZT8V79E5OV";
var $urlDir = $baseDir + "/" + $objectDir + "/" + $idObjectDir + "?ws_key=" + $keyDir + "&output_format=JSON";
// TEST DE LA METHODE PUT SUR L ID D UN CUSTOMER
$.ajax({
type: "PUT",
url: $urlDir,
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
data: {"id": "93"},
crossDomain: true,
success: function () {
console.log("Ok PUT");
},
error: function() {
console.log("Erreur PUT");
}
});
});
Before, I tried to GET the id of an object (same: customer) and I succeeded with an almost similar method.
I precise that I gave rights about "customer" in Advanced Settings / webservice (for method GET, PUT, POST ...).
Thanks in advance for your help, I tried so many things, but whitout success.
PS: If you have any suggestion about my code to "clean" it, you were pleased.
My webservice JSON:
{"customer":{"id":1,"id_default_group":"3","id_lang":"1","newsletter_date_add":"2013-12-13 08:19:15","ip_registration_newsletter":"","last_passwd_gen":"2015-06-08 03:38:27","secure_key":"7036cdf99ea12125ad1b3789f298f686","deleted":"0","passwd":"2e372235eb5213bc004ce72bcfef16a2","lastname":"DOE","firstname":"John","email":"pub#prestashop.com","id_gender":"1","birthday":"1970-01-15","newsletter":"1","optin":"1","website":"","company":"","siret":"","ape":"","outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":"","is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2015-06-08 09:38:27","date_upd":"2015-06-08 09:38:27","associations":{"groups":[{"id":"3"}]}}}
EDIT:
When I tried with the method GET, I did:
$.ajax({
type: "GET",
url: $urlDir,
dataType: "json",
async: false,
success: function (data) {
$scope.customer1 = data;
console.log("Ok GET");
console.log(data);
},
error: function() {
console.log("Erreur GET");
}
});
Reading the status code definition of the http protocol, try adding the following property to the ajax request:
$.ajax({
type: "PUT",
...
beforeSend: function (xhr) {
xhr.setRequestHeader("Allow", "GET, HEAD, PUT, DELETE");
},
...
});
PS: If you have CORS disabled on your server, look this answer and set the headers to allow your server access to requests from different origins.

Categories