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

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.

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
});

Error post AJAX from Spring JAVA

I already created MVC spring and I want consume with SAPUI5 (javascript) with AJAX but I found an error "415 (Unsupported Media Type)". I use swagger in spring for test CRUD. in swagger, I success for insert data but failed in AJAX.
controller Spring:
#PostMapping(value={"/tesinsert"}, consumes={"application/json"})
#ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<?> insert(#RequestBody KasusEntity user) throws Exception {
Map result = new HashMap();
userService.insertTabel(user);
return new ResponseEntity<>(result, HttpStatus.CREATED);
}
in javascript:
var data = {
"kodekasus":5,
"nama":"baru",
"isdelete":1,
"createdby":"hahaa",
"createddate":null,
"updatedby":"hihii",
"updateddate":null
};
$.ajax({
type: 'POST',
url: url,
data: data,
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});
if I code above in AJAX, show error "415 (Unsupported Media Type)", if I add in AJAX show different error: "Response for preflight has invalid HTTP status code 403
":
headers: {
Accept : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
}
How to solve this problem?
Thanks.
Bobby
Add dataType: 'json' in your ajax call:
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
success: function(data) {
console.log('sukses: '+data);
},
error: function(error){
console.log('gagal: '+error);
}
});

Laravel Ajax POST Request does not work: 302 found

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) {
}
});

How to parse a JSON response as JSONP on a jQuery ajax call?

I'm dealing with the todoist API (https://developer.todoist.com/) and I am making a jquery ajax get request for some data with this:
var url = "https://todoist.com/API/v7/sync";
var data = {
'token' : token,
'resource_types' : '["all"]',
};
$.ajax({
url: url,
data: data,
type: 'GET',
dataType: 'jsonp',
success: function(response) {
console.log(response);
},
error: function(response) {
console.log('error');
},
});
Now, when I get the response, I get the error
Unexpected token :
Why? Because according to (https://stackoverflow.com/a/7941973/2724978) jQuery is expecting a jsonp formatted response, but it returns json.
I've researched all over for how to solve this, and the response would be: "Return the data in jsonp format".. well. It's an external API and they don't provide data in JSONP. Is there a way I could override the returned function and parse this JSON data anyway?
Your dataType should be json, not jsonp.
As elektronik pointed out the dataType should be json and not jsonp. The code than looks as following ...
var token = "your token"
var url = "https://todoist.com/API/v7/sync";
var data = {
'token' : token,
'resource_types' : '["all"]',
};
jQuery.ajax({
url: url,
data: data,
type: 'GET',
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(response) {
console.log('error');
},
});

HTTP Authentication failing in AJAX for postmates api

I'm trying to use the postmates API, which first requires us to authenticate ourselves using http basic authentication. The username field in the code below is where we inserted our private API key.
<script>
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); }
});
});
</script>
The error we are getting is
XMLHttpRequest cannot load
http://api.postmates.com/?callback=jQuery112008309037607698633_1462052396724&_=1462052396725.
Response for preflight is invalid (redirect)
need the authentication
https://postmates.com/developer/docs#authentication
The actual header that is used will be a base64-encoded string like
this:
Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==
Try to
$(document).ready(function(){
// Request with custom header
$.ajax({
url: ' http://username:#api.postmates.com',
type: 'GET',
dataType: 'jsonp',
success: function(response) { alert("Success"); },
error: function(error) {alert(error); },
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic Y2YyZjJkNmQtYTMxNC00NGE4LWI2MDAtNTA1M2MwYWYzMTY1Og==");
}
});
});
I don't test because jsfiddle block external petitions.

Categories