Kanbanpad API calls (jQuery AJAX) - ajax

I'm having an issue getting this jQuery.ajax call to work. When the script executes I get an error (textStatus = "error"), but no error message (errorThrown = "").
$.ajax({
type: 'GET',
url: 'http://www.kanbanpad.com/api/v1/projects.json',
username: 'user#example.wtf',
password: 'myAPIkey',
dataType: 'json',
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus+': '+errorThrown);
}
});
If I manually hit the API URL (above) and type in my login credentials, I do get the proper JSON response. So, I'm not sure what I'm doing wrong. Is my code malformed?
If you need more information about the API, go to http://www.kanbanpad.com/api/v1

That page is using HTTP basic auth but you are simply posting a username/password in your request. You have to properly set up the auth tokens and pass them in a header. Here is a simple tutorial on HTTP basic auth over AJAX--notice there is a jQuery specific example for the AJAX part.

Here is the fix:
Change URL value to http://username%40domain.com:apikey#www.kanbanpad.com/api/v1...
For whatever reason, jQuery (1.5.1, also tried with 1.4.4) is not passing the username and password parameters to the web server correctly (or not at all?), so rather than use those parameters, it can authenticate by including the credentials in the URL string.

use secured protocol for URL: https://www.kanbanpad.com/api/v1/projects.json, not http

Related

Avoid CORS in rest API

I'm having a problem to make a call to a rest API.
In the document (FAQ) of the web application there is an example that use AJAX request to make the call. Here an example:
var url = 'https://example.com/yyy';
$.ajax({
type: 'POST',
url: url,
cache: false,
data: {
opt: JSON.stringify(example)
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result)
{
console.log(result);
} });
I created a local page with this code to made the post to the API that is located on a remote server but I receive an error about CORS.
Is there any solution to circumvent this problem? I tried to use firefox plugin to allow CORS but it didn't solve the problem. The session is authenticated via form before use the endpoint.
I see several issues:
Try to run the code from a domain and not from local disk (alternatively you can consider using https://crossorigin.me/ )
How does the authentication work? if with cookies you need to add withCredentials to the ajax request.
Make sure the API returns Access-Control-Allow-Origin: foo header where foo is the domain your code runs in. If you also used withCredentials, you should add Access-Control-Allow-Credentials: true

javascript: how to make AJAX call based on the avaiable cURL request

Currently in my web app project, I need to parse the content of a web page, and after some searching, I found that Mercury Web Parser API is quite suitable for me.
And I have some experience with such kind of third party APIs, generally speaking I can get my desired result.
But for this API, I can't find documentation about the API usage on the official website.
Based on the my study, it provide two methods:
first is cURL as following:
curl -H "x-api-key: myapikey" "https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed"
the myapikey is the API key I get from the website. Then I can get the result in JSON format, which is the main content of the web page specified by the url parameter. It works well for me, I mean the cURL method.
And on the website, it said that the second method is HTTP call, which is just what I need:
GET https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed
Content-Type: application/json
x-api-key: myapikey
So based on my understanding, I use jquery AJAX method to do this as following:
var newurl = "https://mercury.postlight.com/parser?url=http://www.businessinsider.com/joel-spolsky-stack-exchange-interview-2016-12&x-api-key=myapikey"
$.ajax({
url: newurl,
dataType: "jsonp",
success: function(data){
console.log(data.title);
}
})
here I made JSONP request because of the Cross origin issue.
But now I face 401 error message (401 Unauthorized. The request has not been applied because it lacks valid authentication credentials for the target resource)
For now my guess is that the apikey is not correctly passed to server. So based on the cURL's successful call, can I get the correct format for AJAX call?
Update:
Based on the following answers ,I tried to set the request header as following:
$.ajax({
url: newurl,
dataType: "jsonp",
beforeSend: function(xhr){
console.log(apiKey);
xhr.setRequestHeader('x-api-key', apiKey);
},
/*
headers: {
"x-api-key": "M1USTPmJMiRjtbjFNkNap9Z8M5XBb1aEQVXoxS5I",
"contentType": 'application/json'
},
*/
success: function(data){
console.log("debugging")
console.log(data.title);
},
error: function (error) {
console.log(error)
}
})
I tried both beforeSend and headers. But still can't work and get the following trackback error message:
send # jquery.js:8698
ajax # jquery.js:8166
addNewArticle # topcontroller.js:18
fn # VM783:4
e # angular.js:281
$eval # angular.js:147
$apply # angular.js:147
(anonymous) # angular.js:281
dispatch # jquery.js:4435
elemData.handle # jquery.js:4121
And for the last send function, still 401 error.
But the ajax error handling part shows that the readyState:4 and status: 404 result. So what's going here.
For your question, the curl request is sending a header which you have attached as part of the query string in your $.ajax request.
Try the following instead (using beforeSend + xhr) :
// broke this string down so you don't have to scroll
var newurl = "https://mercury.postlight.com/parser?" +
"url=http://www.businessinsider.com/" +
"joel-spolsky-stack-exchange-interview-2016-12";
// set your api key
var apiKey = "<your api key>";
$.ajax({
url: newurl,
dataType: "json",
beforeSend: function(xhr){xhr.setRequestHeader('x-api-key', apiKey);},
success: function(data){
console.log(data.title);
}
})

jQuery Cross Domain Request to get JSON Response without Callback

I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.

POST request to Picasa API

I'v been struggling with POST on the Picasa API.
Here's code:
$.ajax({
type: "POST",
url: 'https://picasaweb.google.com/data/feed/api/user/' + uid + '/albumid/' + album_id + '/photoid/' + photo_id,
crossDomain: true,
data: { content: content },
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
I've already retrieved some information via GET without problems.
Now comes the fun part, when I try to test the service with Google this error occurs:
XMLHttpRequest cannot load
https://picasaweb.google.com/data/feed/api/user/userid/albumid/albumid/photoid/photoid?content=foo%bar.
Origin http://localhost:3000 is not allowed by
Access-Control-Allow-Origin
.
And when I try in Firefox the request header method is changed to OPTIONS and status is 204: no content.
Also, I've tried to change datatype to jsonp but then HTTP method changes to GET and it retrieves information about the picture.
Access-Control-Allow-Origin is coming because your are making a ajax call to a server which is not same as your current domain.
Read more here
jsonp will not help for POST request because you can only make GET request with jsonp.
IMHO you should try to make the POST request from server side instead of client side script.

Basic Authentication and jQuery/ajax call

I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?

Resources