How to send Cross Domain Ajax POST with Laravel - javascript

I am trying to send a cross-domain post call using AJAX from one of my Laravel sites, to another.
The other topic I saw addressed the first issue I was running into with Access Control headers: Jquery: Cross-domain ajax 'POST' with laravel
I am getting a 419 error, implying that I am not using a CSRF token, but with either token I use (local token or other domain token) it doesn't work.
var CSRF_TOKEN = {{ csrf_token() }};
$.ajaxSetup( { headers : { 'X-CSRF-TOKEN' : CSRF_TOKEN } } );
var tracking_id = "{{ isset( $tracking_id ) ? $tracking_id : 'test-20' }}";
$.ajax({
type: 'POST',
url: 'https://example.com/beacon',
crossDomain: true,
data: { 'tracking_id': tracking_id },
success: function(responseData, textStatus, jqXHR) {
console.log( 'Click!' );
},
error: function (responseData, textStatus, errorThrown) {
console.log( responseData );
}
});

Excluding the route in VerifyCsrfToken.php would be your easiest bet. You can then make a middleware or some other means to restrict the request by ip, oauth, etc.
Docs: https://laravel.com/docs/5.7/csrf#csrf-excluding-uris

Related

How to make a REST API Request with Ajax and session token?

I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});

Ajax works periodically. Sometimes POST request return error 419

With the help of Laravel I create a multilingual website. When I switch languages using Ajax, sometimes I get an error.
Javascript code:
$(document).ready(function(){
$("#LanguageSwitcher").change(function(){
var locale = $(this).val();
var _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/language",
type: 'POST',
data: {locale: locale, _token: _token},
datatype: 'json',
beforeSend: function () {
console.log('before send - ' + locale);
},
success: function (data) {
console.log('success');
},
error: function (error) {
console.log(error);
},
complete: function (data) {
window.location.reload(true);
}
});
});
});
web.php:
Route::post('/language/', array(
'before' => 'csrf',
'uses' => 'LanguageController#changeLanguage'
));
Controller:
class LanguageController extends Controller
{
public function changeLanguage(Request $request){
if ($request->ajax()) {
$request->session()->put('locale', $request->locale);
}
}
}
layout.blade.php:
<meta name="csrf-token" content="{{ csrf_token() }}">
<select id="LanguageSwitcher" class="btn btn-outline-danger">
<option>...code...</option>
<option>...code...</option>
<option>...code...</option>
</select>
When I go through another browser everything works. It also works if I go through the incognito mode. Can this be due to the fact that I log in to the admin panel?
Put your ajax call like this.
req = $.ajax({
type: "POST",
url: "/search",
data: {
"locale": locale,
"_token": "{{ csrf_token() }}",
},
dataType: "json",
success: function(msg){
}
});
As I saw your code.
You passing csrf token in your request. the problem you face is, your csrf token is not being updated.
Let's say, you're not reloading your page, on first time your enter to your page, laravel give you csrf token which you providing to ajax through meta.
But after some time on the backend(laravel side). your csrf token is updated, but you don't have updated one in client-side.For get the updating one you need to reload the page.
so for this issue, you need to check whenever you get error status 419, request laravel for new csrf token(by making a new route get the csrf token from laravel helper csrf_token() return back to ajax) and update to your file. and send back that token to laravel with you request.
For updating newly token to your page
document.querySelector('meta[name=csrf-token]').setAttribute('content', res.data.csrf);
or you can refresh your token by reloading the page
add csrf token in meta tag in your blade view
<meta name="csrf-token" content="{{ csrf_token() }}"/>
in your ajax function :
$.ajax({
url: '/search',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
dataType: 'json',
success: function(response) {
},error:function(err){
}
});
I found the answer, but still did not understand how it works, explain who understands this.
App\Exceptions\Handler.php
public function render($request, Exception $exception)
{
// code for updating token when session is expired
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return Redirect::back()->withErrors(['session' => 'Sorry, your session seems to have expired. Try Again']);
}
return parent::render($request, $exception);
}

how to read token from header by js

I'm trying to read token from header by plain java script , so I have two pages
A page request B page by
var B = function(){
$.ajax({
url: 'b.html',
method:'get',
dataType: 'json',
success: function(data) {
//do some handle functions
},
error: function(error){
console.log(error);
},
beforeSend: function(xhr, settings) { xhr.setRequestHeader('Authorization','Bearer ' + access_token ); }
});
}
so, now i want read Authorization access token in B page by javascript !
You can use the XMLHttpRequest.getAllResponseHeaders() method to find the token header and retrieve the response.
More Information can be found at : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

REST request errors in Jquery but not REST Client

I am trying to use the JIRA REST API to preform some requests. One of the first things that you must do, according the docs, is authenticate in some way.
Atlassian offers 2 methods; Basic Auth and Cookie Based Auth, the later of which uses cookies to establish a session.
The issue comes into play when I involve Jquery/JS.
Here is the request when preformed in ARC (Advanced Rest Client) for Chrome:
If I run that request, I will get a HTTP 200 response with the correct JSON, which is what I want.
However, when I attempt to do this with Jquery/JS, I recieve an error every time.
Here is that code:
function cookieLogin() {
//Grab username and password from the fields on the page
var user = $("#loginUsername").val();
var pass = $("#loginPassword").val();
$.ajax({
//URL
url: baseURL + path,
//Method
//type: 'POST', //analogous to 'method'
method: 'POST',
//Headers
accept: 'application/json',
dataType: 'application/json',
contentType: 'application/json',
//Payload to be sent
data:
{
"username": "admin",
"password": "admin"
},
//Responses to HTTP status codes
statusCode: {
200: function () {
alert("Success!");
},
401: function() {
alert("Invalid Credentials");
},
403: function () {
alert("Failed due to CAPTCHA requirement/throttling.")
}
},
success: function (data) {
var result = jQuery.parseJSON(data);
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error!!!");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I have assured that the URL is correct. As you can see, I also hard-coded the credentials (this is merely a test page) just to test as well. I'm not sure why I am receiving errors in JS when I replicated the same thing that worked in ARC.
As per the documentation, I am seeing that "accept" should be "accepts" and "dataType" takes the string "json", not "application/json".

"400 Bad Request" response for AJAX request

I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})

Categories