Tableau: import JSON data from simple REST call - json

I have a REST API (served by an external server) replying JSON formatted data.
From what I read from Tableau doc, there's available:
- WebDataConnector but you have to add a JS overload on your webpages, not very suitable for REST APIs
- importing JSON data from file, but doesn't answer my issue
Isn't there a simple way to integrate JSON data requested via REST call ?

You can use WDC, you are wrong that its not suitable for REST API. So you basically need to create 2 functions for getting fields and data for your datasets from API:
myConnector.getSchema = function (schemaCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data/one",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var flatten = objectFlatten(response)
var columns = []
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
columns.push({
id: id,
alias: key,
dataType: tableauType(flatten[key])
})
}
var table = {
id: "digger_" + JSON.parse(tableau.connectionData)['diggerID'],
alias: tableau.connectionName,
columns: columns
}
schemaCallback([table]);
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
myConnector.getData = function (table, doneCallback) {
$.ajax({
url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data",
type: "GET",
headers: {
'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey']
},
success: function(response){
var data = []
for (var i=0; i < response.length; i++) {
var flatten = objectFlatten(response[i])
var rec = {}
for (var key in flatten) {
var id = key.replace(/[^A-Za-z0-9_]+/g, '')
rec[id] = flatten[key]
}
data.push(rec)
}
table.appendRows(data);
doneCallback();
},
error: function (xhr, ajaxOptions, thrownError) {
tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset.");
}
});
};
For complete code you can check out for source code on github: https://github.com/Diggernaut/diggernaut-wdc

Related

ajax returning json data as undefined

when i run below code.
it makes error and alert "fail error:StntaxError: Unexpected token < in JSON at position 0 data:undefined"
what is the problem ??
$("#a").click(function () {
st_dt = $("#st_dt").val();
end_dt = $("#end_dt").val();
lot_cd = $("#lot_cd").val();
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
var json_1 = JSON.stringify(obj);
$.ajax({
type: "POST",
url: '{{ url_for("get_operid") }}',
data: json_1,
dataType: "JSON",
success: function (data) {
alert("Success\n" + data);
},
error: function (request, status, error, data) {
alert("fail\n" + "error:" + error + "\n data:" + data);
}
});
});
Looking at the code it looks like a Laravel API request using Blade Template or the Function url_for is in Flask... In either case
That means the response for the api request is HTML string instead of
a json response...
i.e. The API request is returning a login page or some HTML page...
To check the response you can open the Chrome Devtools in the Network tab check the response of the API...
what you can try is :
var obj = { st_dt: st_dt, end_dt: end_dt, lot_cd: lot_cd };
console.log(obj);
var json_1 = JSON.stringify(obj);
console.log(json_1);
Then See in browser console what is your object and if the JSON converting your object properly.
If that is ok , Your request should be done currectly. And try to see what are the data you getting as response with:
success: function (data) {
consoel.log('response below');
console.log(data);
}
You will find the error. I hope.

Database Not Showing Data in Json Ajax

This is my view file Book.cshtml script section. The problem coming is that it not fetching my data from my database.
Instead it is giving a error:
alert("Failed! Please try again.")
If I truncate the data from the database it shows ONLY the heading "BOOK ID" "BOOK NAME" "BOOK SERIAL NUMBER" "BOOK AUTHER" "BOOK PUBLISHER NAME"
$(document).ready(function () {
// This is for Get All Data
$("#btnAllBook").click(function () {
$.ajax({
url: "#Url.Action("GetAllBook","Books")",
data: "",
type: "GET",
dataType: "json",
success: function (data)
{
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
// this will use for Get Data based on parameter
$("#btnSearch").click(function () {
$.ajax({
url: "#Url.Action("GetBookWithParameter", "Books")",
data: { prefix: $('#txtSearch').val() },
type: "GET",
dataType: "json",
success: function (data) {
loadData(data);
},
error: function () {
alert("Failed! Please try again.");
}
});
});
function loadData(data) {
// Here we will format & load/show data
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Book ID</th>');
thead.append('<th>Book Name</th>');
thead.append('<th>Book Serial Number</th>');
thead.append('<th>Book Auther</th>');
thead.append('<th>Book Publisher</th>');
tab.append(thead);
$.each(data, function (i, val) {
// Append database data here
var trow = $('<tr></tr>');
trow.append('<td>' + val.BookID + '</td>');
trow.append('<td>' + val.BookName + '</td>');
trow.append('<td>' + val.BookSerialNumber + '</td>');
trow.append('<td>' + val.BookAuther + '</td>');
trow.append('<td>' + val.BookPublisher + '</td>');
tab.append(trow);
});
$("tr:odd", tab).css('background-color', '#C4C4C4');
$("#UpdatePanel").html(tab);
};
});
Looking into the documentation on http://api.jquery.com/jquery.ajax/, the callback error is called because the request failed. Then, I suggest you to check if the url #Url.Action("GetAllBook","Books") is returning the right string of the url, maybe you are trying to request in a url that doesn't exists.
Another point, being about a GET request, I suggest you to check opening in a browser if this URL that you are trying to return data, is returning the JSON data expected as you need to append to the HTML.

ajax json parsing to return related values

I am trying to only parse the information related to a certain "market_name" however I cannot seem to figure out how. The api is located at https://stocks.exchange/api2/ticker which displays information related to the entire exchange. I simply need all of the information returned relating to the "market_name" I am searching for such as ETH_BTC
Ajax:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
last = data.last;
console.log(last);
$("#btcprice").text(last);
},
error: function() {
//alert("Was unable to get info!");
}
});
That's because data is an array of objects, not a single object.
Try:
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function (data) {
// find object
var market = data.find(function (obj) {
return obj.market_name == 'ETH_BTC';
});
$("#btcprice").text(market.last);
},
error: function() {
//alert("Was unable to get info!");
}
});
Use array filter() method to filter out the record having market_name as ETH_BTC.
array.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
DEMO
var jsonObj = [{"min_order_amount":"0.00000010","ask":"0.00000017","bid":"0.0000001","last":"0.00000010","lastDayAgo":"0.00000009","vol":"154955.9586604","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ATR_BTC","market_id":338,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.000032","bid":"0.000012","last":"0.00003200","lastDayAgo":"0.000065","vol":"372.5011152","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ETH_BTC","market_id":35,"updated_time":1527789301,"server_time":1527789301},{"min_order_amount":"0.00000010","ask":"0.00003595","bid":"0.00003","last":"0.00003000","lastDayAgo":"0.00003001","vol":"26.44435669","spread":"0","buy_fee_percent":"0","sell_fee_percent":"0","market_name":"ARDOR_BTC","market_id":262,"updated_time":1527789301,"server_time":1527789301}];
var res = jsonObj.filter(obj => {
return obj.market_name == 'ETH_BTC'
});
console.log(res);
$.ajax({
url: "https://stocks.exchange/api2/ticker",
dataType: 'json',
success: function(data) {
var results = [];
var searchField = "market_name";
var searchVal = "ETH_BTC";
for (var i=0 ; i < data.length ; i++)
{
if (data[i][searchField] == searchVal) {
results.push(data[i]);
}
}
$("#btcprice").text(results[0].last);
},
error: function() {
//alert("Was unable to get info!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is a simple code in which you find what you want simply just change searchVal statically or dynamically according to your need......

Handling oAuth2 access_token expiration

After authentication with Google oauth2.login getting access_token and expires_in. Everithing going great till my token expires. After expiration, when I send again request for data with old token like that:
var URLHead = 'https://www.google.com/fusiontables/api/query?sql='
var URLTable = encodeURI('SELECT id,COUNT() FROM TABLE_ID')
var URLTail = '&access_token='+ old_token +'&jsonCallback=?'
var queryURL = URLHead + URLTable + URLTail
var jqxhr = $.ajax({
type: "GET",
url: queryURL,
dataType: 'jsonp',
success: function (d) {
var max = d.table.rows[0].toString().substr(1)
localStorage.setItem('cpage', Math.ceil(max / localStorage.getItem('delimeter')))
},
error: function(){alert('token_expired')}
})
working on success and giving nothing if token expired. All over the internet can't find clear example how to handle expiration? Shouold I count myself 3600 seconds and delete old_token or is there any elegant way to handle token expiration error?
What does the response look like when the token has expired? The API is not necessarily going to throw an error, just a normal JSON response. The response probably contains something to say that the token has expired which you can therefore use to check on the fly.
Try:
success: function (d) {
if(d.error){
if(d.error == 'invalid_token'){
alert('invalid_token');
}
} else {
// local storage etc
}
}
or (with error handling) :
var request = $.ajax({
url: "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=1/fFBGRNJru1FQd44Az%20%E2%80%8BqT3Zg",
type: "GET",
});
request.done(function(msg) {
// complete
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
​
Heres the fiddle : http://jsfiddle.net/MFe9d/

sending multiple models via json in mvc3

Could not find exact matches for the question (some similar posts found) ..
How can multiple models be send via JSON to MVC3 controller e.g having the following parameters:
public JsonResult Add(Project pr, List<Modules> mod)
{
}
following technique was tried but did not work
function AddModules() {
var pname = $("#ProjectName").val();
var data = new Array();
var modules = new Array();
$("#ModuleTable tr").each(function () {
var row =
{
"ModuleName": $(this).find(".moduleName").val(),
"ModuleDesc": $(this).find(".moduleDesc").val(),
"ModuleSize": $(this).find(".moduleSize").val(),
"StartDate": $(this).find(".startDate").val(),
"ModuleId": "",
"ProjectName": pname
}
modules.push(row);
});
var project =
{
"ProjectName": $("#ProjectName").val(),
"ProjectDescription" : $("#ProjectDescription").val(),
"StartDate" : $("#ProjectStartDate").val(),
"ModuleName" : modules
}
data.push(project);
$.ajax({
url: "AddProject",
data: JSON.stringify(data),
type: "post",
contentType: "application/json; charset = utf-8",
dataType: "json",
success: function (status) {
alert(status);
}
});
}
The project class also contains a List type of Module class.
You are sending a string of JSON back to the server, so you have a type difference. Try something like this instead:
Client Side
var myFunction = function(){
var projectName = $("#ProjectName").val();
var projectDescription = $("#ProjectDescription").val();
$.post("[URL TO YOUR CONTROLLER]",{pName : projectName, pDescription: projectDescription},function(response){
alert(response);
});
};
Server Side
public ActionResult MyActionResult(FormCollection fc)
{
var projectName = fc["pName"];
var projectDescription = fc["pDescription"];
var result = projectName + " hase been posted!";
return Content(result);
}
Good luck!