Consuming OData Servie using DataJS - javascript

I have this javascript code in MVC view i try to call OData Service using Datajs :
$(document).ready(function() {
var temp = OData.read("http://odata.netflix.com/v1/Catalog/Genres", function (data, response) {
var x = 3;
});
});
i have a break-point on var x = 3; but unfortunately the break-point was never hit! if i put break-point on OData.Read i can see its calling the OData-Service but then the callback function never get fired , i dont know what im doing wrong?

Add this before calling OData.Read():
OData.defaultHttpClient.enableJsonpCallback = true;
Also your request doesn't specify format. Change the request string to: http://odata.netflix.com/v1/Catalog/Genres?$format=json&$callback=?callbackHere

Related

.length undefined only after setTimeout

I am trying to load the results of a GET request from the twitter api in a nodejs file held on AWS. Currently the code runs once and console.log's the feed when loading the file in the terminal but when I use setTimeout to try to refresh the results i get .length undefined.
Currently my code looks like this...
var Twit = require('twit');
var config = require('./config.js');
var T = new Twit(config);
var params = {
exclude_replies: true,
count: 20,
include_entities: false
};
T.get('statuses/home_timeline', params, gotData);
function gotData(err, data, response) {
var timeLine = data;
for (var i = 0; i < timeLine.length; i++) {
var obj = timeLine[i];
console.log(obj.user.name);
};
};
setTimeout(gotData, 10000);
I have reviewed other questions relating to setInterval and .length issues but I've been unable to find anything I was able to apply to this issue
Thanks for any help you can give me
setTimeout(gotData, 10000); invoke gotData without any parameters where as T.get('statuses/home_timeline', params, gotData); invoke it passing retrieved data.
Try following
setTimeout(function() {
T.get('statuses/home_timeline', params, gotData);
}, 10000);
You have to call the GET request again after the timeout, unless the gotdata function is invoked without passing response data. Try something like this.
setTimeout(function(){
T.get('statuses/home_timeline', params, gotData);
}, 10000);
Your goData() function expects three parameters:
function gotData(err, data, response)
But you are calling it without any params in T.get('statuses/home_timeline', params, gotData) and setTimeout(gotData, 10000), that's why you will get this exception because data is undefined in:

Reading file with Javascript into array - can't seem to make it work

I have a simple 2-column csv file that I would like my site to read and ultimately parse into an array. The data is in the following format:
Atlanta Braves, Atlanta_Braves
Baltimore Orioles, Baltimore_Orioles
Boston Red Sox, Boston_Red_Sox
etc.
The file is currently stored in the same location as my html file. I am trying to use an ajax request to pull the data from the file into an array, then parse further such that myArray[0][0] = 'Atlanta Braves'.
Here is my code:
var myArray = [];
$.ajax({
type: 'GET',
url: 'datafilename.csv',
success: function(data){processData(data);}
});
function processData(data){
myArray = data.split('\n');
for (i = 0; i < myArray.length; i++){
myArray[i] = myArray[i].split(',');
}
}
alert(myArray[0][0]);
Unfortunately, the alert only returns 'undefined'. What am I doing wrong here? Any feedback would be appreciated.
$.ajax is an asynchronous function. That means that it won't complete until sometime later, after your other synchronous code has already run. Try adding this:
function processData(data) {
// Your existing code goes here...
alert(myArray[0][0]);
}
This works because processData is only run after the AJAX call has returned. Asynchronous functions basically work like this:
var value = 1;
setTimeout(function() {
value = 2; // This won't happen for about 1 second
console.log(value); // 2
}, 1000); // Run this function in 1 second
console.log(value); // 1. This happens almost immediately, without pause

$http Call to Web API 2 Not Passing Parameter

This is my C# WebAPI2 controller, which gets hit:
[HttpGet, Route("bycaseidlist/{idArray}")]
public async Task<IHttpActionResult> GetByCaseIdList([FromUri] List<int> idArray)
This is the call:
var idArray = [4,4,2,4];
var url = baseUrl + 'api/cases/bycaseidlist/' + idArray ;
$http.get(url)
The problem is that the API doesn't get the array, it gets ...this:
In other words an array with one value: 0. Why is this happening? How do I fix it? It seems to be in-line with this answer, but it doesn't work. Should I pass it in the body? I feel like I am missing something obvious.
Get ActionMethods can take objects as arguments. However, the default behavior is to look at the body when the parameter is not a .net primitive. In order to force the action method to use a model binder to read the object data from the request, the parameter can be decorated with the [FromUri] or [ModelBinder] attributes. (Note there are other ways to do this that include doing parameter binding rules but that is probably overkill for what you are trying to accomplish here). Here is an implementation that solves the original problem that you were posing.
<script type="text/javascript">
var ajaxCall = function (myArry) {
var ajaxProperties = {};
ajaxProperties.url = "/api/Mul/Mutiply";
ajaxProperties.type = "Get";
ajaxProperties.data = {};
ajaxProperties.data.numbers = myArry;
ajaxProperties.contentType = "application/json";
console.log(ajaxProperties);
ajaxProperties.success = function (data) {
console.log(data);
}
ajaxProperties.error = function (jqXHR) {
console.log(jqXHR);
};
$.ajax(ajaxProperties);
};
var getData = function (e) {
var myArry = new Array();
myArry.push($('input[name=num1').val());
myArry.push($('input[name=num2').val());
ajaxCall(myArry);
return false;
};
</script>
Controller
[HttpGet]
public IHttpActionResult Multiply([FromUri] int[] numbers)
{
int result = 0;
if(numbers.Length > 0)
{
result = 1;
foreach (int i in numbers)
{
result = result * i;
}
}
return Ok(result);
}
}
I think my mistake was using Get. I might be remembering incorrectly (someone confirm if you know offhand), but Get might not be able to take objects as arguments. Anyway, I changed the method to POST and then changed the param to be sent in the request body, rather than the url. It now works. Here is the working code:
[HttpPost, Route("bycaseidlist")]
public async Task<IHttpActionResult> PostByCaseIdList([FromBody] int[] sqlCaseIdArray)
and the call itself:
function runDbCall(url, sqlCaseIdArray){
return $http({
method: 'POST',
url: url,
data: sqlCaseIdArray
});
}
runDbCall(url, sqlCaseIdArray)
I will come back to this when I figure out if the problem was Get not being able to take objects, but I thought it could in url, just not in body...need to clarify. If someone posts an answer just on that part, I will accept, since that's probably the root of the prob.

jQuery .push into an Array in a .get call gives an empty result

Can anyone tell me why the below gives me an empty string? When I console.log(contentArray) in the $.get() callback function it shows the data but when I try to do it where it is in the code below, the result is empty.
sectionArray = [];
contentArray = [];
$(function () {
if (index == 1) {
$('menu:eq(' + (section - 1) + ') li a').each(function () {
sectionArray.push($(this).attr('href'));
});
var len = sectionArray.length;
for (var i = 0; i < len; i++) {
href2 = sectionArray[i];
$.get(href2, function (data) {
string = data.toString();
contentArray.push(string);
});
}
content = contentArray.toString();
console.log(content);
}
because ajax request ends after you call console.log() try this:
$.get(href2, function(data){
string = data.toString();
contentArray.push(string);
content = contentArray.toString();
console.log(content);
});
also do ajax request in loop is not best thing to do. that wont work as you want.
UPDATE:
also jQuery has async option set to false and your code should work but will work slow. Synchronous requests may temporarily lock the browser.
UPDATE 2
maybe try something like this(maybe not so good idea :D):
var countRequests = len;
$.get(href2, function(data){
string = data.toString();
contentArray.push(string);
countRequests = countRequests - 1;
if (countRequests == 0) {
content = contentArray.toString();
console.log(content);
// or create callback
}
});
The problem is that your $.get() ajax requests are executed asynchronously.
That is, the $.get() function returns immediately without waiting for the response, your entire for loop completes (queueing up multiple ajax requests), then your console.log() occurs at which point the array is still empty. Only after that do any of the ajax success handlers get called, regardless of how fast the ajax responses come back.
EDIT: Here is an answer from another question that shows how to do something after all the ajax calls have completed: https://stackoverflow.com/a/6250103/615754

jQuery getJSON never enters its callback function

I've been sitting with this for hours now, and I cant understand why.
q is working. The URL does give me a proper JSON-response. It shows up as objects and arrays and whatnot under the JSON tab under the Net-tab in Firebug and all is fine. I've also tried with other URLs that i know work. Same thing happens.
I have another function elsewhere in my tiny app, wihch works fine, and is pretty much exactly the same thing, just another API and is called from elsewhere. Works fine, and the data variable is filled when it enters the getJSON-function. Here, data never gets filled with anything.
I've had breakpoints on every single line in Firebug, with no result. Nothing happens. It simply reaches the getJSON-line, and then skips to the debugger-statement after the function.
var usedTagCount = 10;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
for(var i = 0; i < usedTagCount; i++) {
tagString += query[i].key + ",";
}
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
debugger; /* It never gets here! */
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
debugger;
return flickrImageData;
}
Example of request URL (q):
http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=20&jsoncallback=?&tags=london,senior,iphone,royal,year,security,project,records,online,after,
I do wonder, since JSONView (the firefox plugin) cannot format it properly, that it isn't really JSON that is returned - the mime-type is text/html. Firebug, however, interprets it as JSON (as i stated above). And all the tag words come from another part of the app.
I think you might need to remove the
nojsoncallback=1
from your searchAPI string.
Flickr uses JSONP to enable cross domain calls. This method requires the JSON to be wrapped in a json callback, the nojsoncallback=1 parameter removes this wrapping.
EDIT: Apparently it works with nojsoncallback=1, I got this piece of code to work for me. What jQuery version are you using? JSONP is only available from 1.2 and up.
This works for me (slight modifications):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
var usedTagCount = 1;
var searchHits = 20;
var apiKey = "a68277b574f4529ace610c2c8386b0ba";
var searchAPI = "http://www.flickr.com/services/rest/?method=flickr.photos.search&" +
"format=json&api_key=" + apiKey + "&sort=interestingness-desc&per_page="
+ searchHits + "&jsoncallback=?&nojsoncallback=1&tags=";
var tagString = "";
var flickrImageData = new Array();
function search(query) {
tagString = query;
var q = searchAPI + tagString;
$.getJSON(q, function(data) {
$.each(data.photos.photo, function(i, item) {
debugger;
flickrImageData.push(item);
});
});
}
search("cat");
</script>
When I try the url: http://www.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=a68277b574f4529ace610c2c8386b0ba&sort=interestingness-desc&per_page=10&tags=mongo
it returns data, as it should -
try to change the getJSON to an $.ajax() and define a function jsonFlickrApi (data)
with the code you have in you callback function.
If that don't work - please post code to at jsbin.com <- so we can try it live - so much easier to debug.

Categories