Box Get an Access token with ajax - box-api

I need to get the Access Token in ajax, the following example is in Curl how can i do the same in ajax call?
curl https://www.box.com/api/oauth2/token \
-d 'grant_type=authorization_code&code={your_code}&client_id={your_client_id}&client_secret={your_client_secret}' \
-X POST

i send ajax as following:
$.ajax({
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20https%3A%2F%2Fwww.box.com/api/oauth2/token',
type: 'POST',
dataType: 'jsonp',
processData: false,
data: {grant_type:'authorization_code', client_id:'3d2yi406h9eoykhucw9b8w3d2oky7kdy' , client_secret:'YQtHVIoutEnKLNpbmjk3CvZ72bshnpGk'},
complete: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
})
XMLHttpRequest {statusText: "", status: 0, response: "", responseType: "", responseXML: null…}
Alert: {"statusText":"OK","status":200,"response":"","responseType":"","responseXML":null,"responseText":"","upload":{"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null},"withCredentials":false,"readyState":4,"timeout":0,"ontimeout":null,"onprogress":null,"onloadstart":null,"onloadend":null,"onload":null,"onerror":null,"onabort":null}
As you can see i get an status:200 but the response is empty, and not including an "Access token", why?

If you look here: http://developers.box.com/oauth/
You will see that in the section "Getting the Access Token" that you can provide a redirect_uri.
When you register your application with Box they present you a page where you enter what is the redirect url that will be used (see example from link above). However, you can override that and provide the redirect url on your call during oAuth. So all you have to do is provide a page on your own web site which will hold the state change (either success or failure), and check on the state.
I saw that you added another detail on the request.
Note that the request is being done to https://query.yahooapis.com/v1/public/y... instead of http://developers.box.com/oauth/. That redirection is probably changing the query or the headers. Try updating and resubmitting. Let me know if it doesn't work.

Related

How to grab REST API data and display in a html page

Hi i am trying to get data from my LMS's rest API and then display it on a html page, I have a URL and an authorization bearer key
I was provided with some examples of how I should show my url and where to place my Authorization key see below
GET https://example.thoughtindustries.com/incoming/v2/ping
Example Request
CURL https://example.thoughtindustries.com/incoming/v2/ping -H 'Authorization: Bearer APIKEY'
I get a call back using the CURL in Visual Studio code so i know it can be pulled.
I found this method online which I thought would work
$.ajax({
url: "https://api.apiscience.com/v1/monitors/1572022",
headers: {
"Authorization": "Bearer NN_6xxxxx"
}
}).done(function(data) {
$('#monitor_data').append(JSON.stringify(data))
});
<h2>Response Data</h2>
<div id="monitor_data">
<!--location for Javascript to print data-->
</div>
I thought this would be the answer when replacing with my own URL and key but nothing happened. Do I need to include the -H somewhere and if so what might that look like?
It's easy as you have already done this. Write a get ajax call to your API and render your html part from the response you get from the API.
Take a sample example:
var getGamePeriod = function(){
$.ajax({
type: "GET",
url: "yourendpointhere?param=val",
contentType: "application/json",
dataType : 'json',
success : function(response){
if(response && response.isSuccess){
// do your stuffs here..
}
},
error : function(data,textStatus,errorMessage){
alert( textStatus + " " + errorMessage);
}
});
}
Of course you need to pass header or auth token if it is required to access the API. Place this method under document.ready method.

JSON is Malformed in Fetch POST request using React Native

I have a function in a React Native app that is supposed to send data to a server that I'm hosting. This function seems to be throwing errors though every time I press submit and this function is called. The function should be sending a POST request to my webserver and receive information back. It has no problem receiving information but sending is another story... The current code below is giving me an error that says "JSON Parse error: Unrecognized token '<'. But as you can see in my code below I do not even have that symbol present in the 2nd parameter of the fetch function. Occasionally, when I tweak what I have I get an error that also says 'JSON Parse error: Unexpected EOF'. I am not sure how exactly this request is I guess 'malformed'. I am pulling it straight from the docs given by Facebook. I have also tried Axiom & XMLHttpRequest and I am still seeing similar JSON errors. Anyone?
login = () => {
// check if the username is being passed off properly...
//alert(this.state.username);
fetch('MYURL', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
})
})
.then(function(response){ return response.json(); }) // transforms response into data that is readable for this app...
.then(function(data) {
console.log(data);
})
.done();
}
When I shoot that post request in Postman I get back header "Content-Type: text/html; charset=UTF-8". So you don't get json back at all, that's why it doesn't work. I would venture that you have to add the correct application/json header in your backend.

Ajax request Syntax issue

Here my code in sencha for receiving JSON data, Problem is when i call is always shows the error message because of syntax.I dont know where it fails coz im new to sencha,Here my code
Ext.Ajax.request({
url: 'http://117.218.59.157:8080/WishList/Login',
method: 'POST',
headers: { 'Content-Type': 'application/json;' },
jsonData:{
username : "faz#gmail.com",
emailId : "faz"
},
success: function (response)
{
alert(response.responseText);
},
failure: function (response)
{
alert(response.responseText);
}
});
When the above method calls it showing the following response
<html><head><title>Apache Tomcat/7.0.14 - Error report</title><style><!--H1 {font-
family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;}
H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-
size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-
color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-
serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-
serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-
serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color :
black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 404 - </h1><HR
size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The requested resource () is not available.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.14</h3></body></html>
I call the JSON url in fiddler as in the following format
Method: POST
URL: http://117.218.59.157:8080/WishList/Login
Request:
{
"emailID": "xy#gmail.com",
"password": "ganesh"
}
Response:
[
{
"response": "Success"
}
]
I dont know where my code fails .please help me to sort it out
HTTP status 404 means "resource not found." The server at 117.218.59.157:8080 isn't configured to serve a resource on the path /WishList/Login. You'll have to look at the server configuration/code to figure out why that is. Note that some HTTP servers are case-sensitive, and so (for instance) WishList and Wishlist may not be the same thing to the server.
Personally I use a google chrome extension to check the services I call via Ajax in order to make sure they are OK. This one helped me a lot you just put your URL in there and mimics the GET/POST -- https://chrome.google.com/webstore/detail/advanced-rest-client/hgmloofddffdnphfgcellkdfbfbjeloo
Good Luck!

Posting parameters in one URL and getting JSON from another URL

Am working in jQueryMobile and PhoneGap.
Currently am facing an issue that; For get the details in JSON format ; I post parameters into an URL (URL1) and I get the JSON response from another URL (URL2)
Currently i cant access the JSON data from the second URL.
My code is ;
function proceed_payment(){
var cardholder_= $('#input_Cardholder_name_').val();
var card_num_ = $('#input_CreditCard_').val();
var payment_ =$('#card_type_').val();
var cvv2_=$('#input_cvv2_').val();
var url;
url='https://www.sample.com/json/save_pament.php?json=1&rcg_mobile=2&reserv_num='+reservation_number+'&callback='+reservation_carcompany+'&cardholder='+cardholder_+'&payment='+payment_+'&card_num='+card_num_+'&card_cvv2='+cvv2_+'&card_expire_mon='+expire_month+'&card_expire_year='+expire_year+'&org_deposit='+sCarDeposit+'&org_cur='+currency+'&mond='+company_Show_mond+''
$.ajax({
url:url,
data:'',
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
crossDomain:true,
cache: false,
async:false,
success:function(data)
{
alert(data.Status);
$.mobile.changePage( "#reservation_status", {reverse: false, changeHash: true});
event.preventDefault();
},
error: OnError
});
};
Here I Post the parameters to URL1 : - https://www.sample.com/json/save_pament.php?
and get the JSON result in URL2 : https:// www.sample.com /result_bank_eup6.php?app=1
But My problem is i cant access the result from URL2.
Is there any method for solve this?
Please HELP :-(
Ullas Mohan V.
As per our discussion in comments and the error you mentioned
( [object Object]-parseerror-SyntaxError: Unexpected token < ).
The issue is related to web service/server side
Web service is not sending the desired response.
So client side/$ajax is not able to parse it.
You can check the actual response using Google Chrome's Advance REST Client.
To resolve this issue, you should contact the company
which is developing server side for you.

Consuming broadbandmap.gov json service errors

I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).