rest api authorize using javascript - javascript

I was trying to create a api web data connector for tableau, but stuck in the authorization phase. I have a header key and value (e.g. api_header, value123) needs to pass using javascript.
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("https://testapi/data",
function(resp) {
var tableData = [];
How to pass the key and value here?

I'm not sure .getJSON supports headers, at least the documentation doesn't mention them.
According to this answer, you could use .ajax instead like so:
$.ajax({
url: 'https://testapi/data',
headers: { api_header: 'value123' }
});

Related

Best way to transport data on MVC using jQuery?

I have an Inbox with internal messages from my clients. When I click on the list over the name I'm requesting using jQuery $.ajax so:
$.ajax({
url: 'messages/retrieve/' + client_id,
}).done( function(data) {
$('.messages-dialog').html(data);
});
My controller should return a variable with json data? I understand it should dump it on a view and I should treat it there but how to do it if is client side?
I don't know if is better to treat and create the html structure into controller and than just load it in .messages-dialog with jQuery.html();
Sorry I'm a little lost on that issue.
You can use jQuery.ajax() method, as in the example above. Also see the official documentation with examples http://api.jquery.com/jquery.ajax/.
Besides you can use jQuery.get() and jQuery.post() methods depending on how and what you will send. You can use this methods as shown below:
var url = 'messages/retrieve/' + client_id;
$.post( // for example
url,
function( data ) {
$('.messages-dialog').html(data);
});
See official documentation with examples here: http://api.jquery.com/get/, http://api.jquery.com/jQuery.post/.
Server handler should be like as below:
use JsonResponse; // you must specify the exact component (I use this)
/**
* Change message in dialog // for example
*/
public function changeDialogMessageAction(Request $request) {
// request data processing
$response = new JsonResponse();
$response->setData(array(
// new data for returning to client
));
return $response; // your data, which will be handled in callback
}
You shouldn't create HTML structure in the controller. It's bad style! JavaScript has asynchronous event model, and you should use it. Controller must handle / transform data, which were passed by you and then return back. jQuery callback must embed received handled / transformed data in DOM.

Cannot retrieve JSON data from Last.FM's API

I am working on a school project and have run into trouble. Namely, I am building a simple AngularJS app which shows some kind of a radio chart based on Last.FM's data.
However, when trying to access the API, I never get a response.
This is the code that I use for accessing:
APIservice.getChartTracks = function () {
return $http({
method: 'JSONP',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
}
Afterwards, when I do something like this:
APIservice.getChartTracks().success(function (response) {
$scope.tracks = response.tracks.track;
});
the success() method never gets called. If I were to change the url to this one (found it on some online tutorial), I get a response and everything.
How should I go about accessing Last.FM's API?
Thanks in advance.
With $http, the method to use is GET, not JSONP. Write:
return $http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json'
});
Or use the shortcut:
return $http.get('http://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=MY_API_KEY&format=json');

Fetch data from a complex JSON

I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.
Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});
success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem

Loading JSON from Dojo JsonRest into object variable

According to this post Remove String from JSON, I want to fill a Dojo Selectbox with JSON Data. The Problem is that I have to change the JSON Data before I can handout the data to the dijit.form.select Box.
I get the data via JsonRest. The question if, how I can load the Json Data into a normal object variable? I tried this here but it did not work.
var processStore = new JsonRest({
target: "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit",
headers: {"Authorization": "Basic a2VybWl0Omtlcm1pdA=="},
allowNoTrailingSlash: false
});
var processes = processStore.query("",{});
I simply want to load the JSON data from the JsonRest store in a normal variable.
Thank you
The JsonRest store only accepts an array, so you're not able to retrieve the data, because your store is not able to read that data for you.
If you're only interested in reading the data (so no updating/creating/deleting has to be done), the easiest way is to retrieve that data using an AJAX request and manually put it inside a dojo/store/Memory store, for example:
require([ "dojo/request/xhr", "dojo/store/Memory" ], function(xhr) {
var url = "http://cnwin.ebusiness.local/activiti-rest/service/repository/process-definitions?startableByUser=kermit";
xhr(url, {
handleAs: json
}).then(function(data) {
if (data.data !== undefined) {
var myStore = new Memory({
data: data.data
});
// Do something with "myStore"
});
});
If you're interested in the full capabilities of the JsonRest store, you will have to extend it by yourself. If you look at the code you can see several AJAX requests, in:
get()
put()
remove()
query()
Now you can write your own store and extend those methods.

Request RESTful route in HERE Javascript API

There exist some parameters in the HERE Advanced Routing REST API which is not available in the Javascript API. Is it possible to combine the two APIs somehow (ie. request json route from REST API and display it in the Javascript map?)
The JavaScript API just maps the REST API up in a nice package but there is nothing unique about it. You should be able to call any of the REST API functions with jQuery using $.ajax. Looking at the API explorer I see that they use query parameters for most things so you will want to use the data attribute for all the params.
$.ajax({
url: "http://image.maps.cit.api.here.com/mapview/1.6/route",
type: "GET",
data: {
app_id: "xxxxx",
app_code: "xxxxx",
r0: "52.5338,13.2966,52.538361,13.325329"
r1: "52.540867,13.262444"
...
},
success: function () {...}
error: function () {...}
});
I actually ended up implementing this a bit differently, but I think both ways work equally well. The important part that gave me grief was the &routeattributes=all. Without it, shapes aren't returned so you can't draw the polyline, etc. In the PDF doc it's referred to as responseattributes in a few places which really messed me up. Anyways, I did:
var url = "https://route.st.nlp.nokia.com/routing/6.2/calculateroute.json?
app_id=XXX&app_code=XXX&routeattributes=all&jsoncallback=myCallBackFunction
&jsonattributes=41&waypoint0=[...]";
and then:
var script = document.createElement('script');
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
and
var myCallBackFunction = function (data) { ... }

Categories