AJAX call to Justin TV API failing with JSON format - ajax

I'm trying to make a simple AJAX call to the Justin TV API, which seems to be failing consistently.
When making the AJAX call with url1, the console reports Object { readyState=4, status=200, statusText="success"}, yet it falls into the error function of the AJAX call. When visiting the URL with my browser, I notice the returned data is [{ ... json ...}].
When making the AJAX call with 'url', the call passes, entering the success function. I notice the returned object is { ...json... }.
How do I get a valid JSON object out of the AJAX request for url1?
Here's a snip of what I'm doing:
var url1 = "http://api.justin.tv/api/stream/list.json"
var url = "https://api.twitch.tv/kraken/streams/";
channelNames = "";
for (channelName in streams)
{
channelNames = channelNames + ',' + channelName;
}
channelNames = channelNames.slice(1);
console.log(channelNames);
console.log(url1);
$.ajax({
url: url1,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
data: { channel : channelNames },
success: function(data)
{
console.log(data);
if(data.streams.length > 0)
{
$("#streamStatus").html("<ul class='zebra'>");
for(i = 0; i < data.streams.length; i++)
{
stream = data.streams[i];
channel = data.streams[i].channel;
listItem = "<li id='stream"+i+"'>";
streamName = "<span class='name'>" + streams[stream.name.slice(10)] + "</span>";
viewers = "<span class='viewers'>viewers:" + stream.viewers + "</span>";
gameName = "<div class='game'>" + ((channel.game != null) ? channel.game : "No Game Specified") + "</div>";
listItem += streamName + viewers + gameName + "</li>";
screenCap = "<div class='screenCap' style='display:none;'>" + channel.screen_cap_url_small + "</div>"
$("#streamStatus ul.zebra").append(listItem);
$("#streamStatus ul.zebra").append(screenCap);
//console.log(channel);
}
$("#streamStatus").append("</ul>");
}
},
error: function(data)
{
console.log(data);
}
EDIT: Here is the working solution...
var url1 = "http://api.justin.tv/api/stream/list.json"
var url = "https://api.twitch.tv/kraken/streams/";
channelNames = "";
for (channelName in streams)
{
channelNames = channelNames + ',' + channelName;
}
channelNames = channelNames.slice(1);
console.log(channelNames);
console.log(url1);
$.ajax({
url: url1,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
jsonp: 'jsonp',
data: { channel : channelNames },
success: function(data)
{
...
},
error: function(data)
{
console.log(data);
}

You're passing jsonp as the dataType in the ajax call. They're not interchangeable.
As you've noted yourself, the data returned from url1 is JSON, not JSONP: JSONP requires wrapping the returned JSON data in a javascript function call.
A mismatch like this between dataType and the data in the response body will always cause the ajax call to fail.

Related

Error In Ajax Call In html

If I Run The Following Code It's Directly Go To Error:Ajax Failed And Error Show on Fire Bug [Reference Error: Ajax Failed is not defined"].
Plz Tell Where I Make Mistake....?
Its My base 64 Encode Value For Name,Email,Gender,Password
var encodeRname = Base64.encode(name);
var encodeRemail = Base64.encode(email);
var encodeRgender = Base64.encode(lookingfor);
var encodeRpwd = Base64.encode(Pword);
var test = '.1!qkr*';
var decodertr = Base64.decode(test);
IT's My AJAX Call For Post
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("success");
}
function AjaxFailed(result) {
alert('Error is : ' + result.status + ' ' + result.statusText);
}
Your error handling function must be defined like the following:
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: function (error) {
// your error handling
}
});

Force.com : Rest API Bad Request in Query Like

I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");

Soundcloud likes/favorites

I am trying to load soundcloud likes (used to be favorites), but I am not getting any results from the ajax query.
This is the url I am trying to load: http://soundcloud.com/gazebo-fm/likes
function soundCloudTrackData(linkUrl) {
var url = soundCloudApiUrl(linkUrl, soundcloudApiKey);
$.ajax({
url: url,
dataType: 'jsonp',
cache: false
}).done(function( data ) {
console.log(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Soundcloud process error: ' + jqXHR.responseText);
});
}
function soundCloudApiUrl(url, soundcloudApiKey) {
var useSandBox = false;
var domain = useSandBox ? 'sandbox-soundcloud.com' : 'soundcloud.com'
return (/api\./.test(url) ? url + '?' : 'http://api.' + domain +'/resolve?url=' + url + '&') + 'format=json&consumer_key=' + apiKey +'&callback=?';
};
change the url to http://soundcloud.com/gazebo-fm/favorites
/likes is used in new soundcloud's api, which is not yet documented.

CFWheels Pagination using AJAX

I've searched the entire Internet, all of it, and cannot find an answer to this.
I'm using the ColdFusion CFWheels Framework to query a database. The query is done via AJAX like this:
var id = $("#ship-id").val();
$.ajax({
type: "POST",
url: "/my-controller/my-method?format=json",
data: {shipId: id},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});
I need to paginate that result set. In CFWheels you normally do that by setting the handle, page, perPage and order values in the query like this:
var order = model("order").findAll(
select="id, firstname, lastname, email",
where="orderid IN (#ValueList(orders.id)#)",
handle="ordersQuery",
page=params.page,
perPage=5,
order="lastname"
);
Then you just put this line in your view:
<cfoutput>#paginationLinks(handle="ordersQuery")#</cfoutput>
But... how in the heck can you get pagination to work with an AJAX call?
I think that something along these lines might be your answer (notice I removed the url and added those params to data ...
$.ajax({
type: "POST",
data: {
shipId: id,
controller: myController,
action: myAction,
page: params.page,
},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

Resources