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

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

Related

Github API v3: Update file not working (404)

I'm trying to update a file using the Github v3 api. Most of the documentation I could find was based on the older API. I want to utilize: https://developer.github.com/v3/repos/contents/#update-a-file
I first grab the file using:
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var jsonFile = data.content;
sha = data.sha;
var decodedJson = atob(jsonFile);
var parsedDecodedJson = JSON.parse(decodedJson);
parseData(parsedDecodedJson);
},
error: function(error){
alert.addClass('alert-danger').removeClass('hidden').html('Something went wrong:'+error.responseText);
}
});
Which works perfectly.
After editing the file, I try to update the file.
On my submit I post the following using jQuery:
var postData = {
"message": "Update",
"content": btoa(obj),
"sha": sha,
"branch":"gh-pages"
};
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'PUT',
data: postData,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("Success!!!", data);
},
error: function(error){
console.log("Cannot get data", error);
}
});
All the variables contain the expected values. Regardless, I keep getting a 404.
I know the API more often than not returns a 404 instead of something like a 403 as stated here: https://developer.github.com/v3/#authentication But it makes debuggin nearly impossible in my opinion. I have no clue what I'm doing wrong here. Thanks!
The only way I was able to do it is to make the entire round trip.
I used a javascript Github API wrapper
Luckily I found this article in which the bulk of the work was already been done. Props to Illia Kolodiazhnyi.
In the end. I ended up with this:
Handler on top of github api plugin
Usage:
var api = new GithubAPI({ token: token});
api.setRepo(owner, repo);
api.setBranch(branch).then(function () {
return api.pushFiles(
'CMS Update',
[
{
content: JsonData,
path: path
}
]
);
}).then(function () {
console.log('Files committed!');
});

How to use an API Key for an Ajax call?

I am trying to include an API key for the first time from New York Times API ( http://developer.nytimes.com/) and use ajax to fetch news from it to populate a local website but I'm not seeing any results. I was told to Make sure your API key is set in the URL's query parameters but I'm not sure how to do it.
?api-key=your-key
Here is what I have done:
// Built by LucyBot. www.lucybot.com
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "111111111111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
I need to see the url in json format for various stories such as business, technology, etc and use them for an ajax call.
Try this I am getting data from this
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "11111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can also try like as follows
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
data: {
'api-key': '11111111111111111'
},
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Its not a good practice expose API Key directly in client-side context.
I strongly recommend to create an abstraction layer between the browser and the API.
The idea is target the AJAX request to one own backend action, like:
var url = "www.mydomain.com/api/articlesearch";
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
And inside the backend (/api/articlesearch) we place the request that target to NY Times, using the API Key
This way you get a more suitable code for javascript, keeping the responsibilities correctly distributed.
PS: If you want it even more safe, you can define the API Key using env variables. Here is an example made in Ruby (just for figure it):
# Inside ApisController
def articlesearch
response = RestClient::Request.execute(
method: :get,
url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
headers: {api_key: ENV['API_KEY']})
render json: response
end
Using this approach the API Key will also not be present in GIT repository :)
Well, you should try it this way. It should give you a result without cross-origin errors:
$.ajax({
type: 'GET',
url: 'http://api.nytimes.com/svc/search/v2/articlesearch.json',
data: {
'q': queryString,
'response-format': "jsonp",
'api-key': nytApiKey,
},
success: function(data) {
// passed function object for data processing
console.log(data);
},
error: function(err) {
console.log('error:' + err)
}
});

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

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.

Facebook Graph jQuery AJAX call to post a photo on user's behalf

I'm trying to post a photo on the users behalf. I've been searching the web for the last 4 hours and I'm out of ideas.
JS:
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})
the error function outputs the following:
[object Object]|error|Bad Request
I think there must be something wrong with the ajax request itself, but I can't figure out what it is. I've reconstructed my request using the Facebook Graph API explorer and everything works fine there. Any ideas?
Need to define the correct data type in the ajax request ( jsonp ), just try this will work :
$.ajax({
type: 'POST',
url: 'https://graph.facebook.com/v2.0/me/photos',
data: JSON.stringify({
url: 'https://www.facebook.com/images/fb_icon_325x325.png',
access_token: token
}),
dataType: "jsonp", //Just add this line ( jsonp not json ),
success: function(data){
console.log(data);
},
error: function(a,b,c){
console.log(a+'|'+b+'|'+c);
}
})

Categories