Jquery Ajax - Tumblr API v2 - ajax

I'm trying to delve into the depths of the murky world of Tumblr, and can't understand how to get over the following error:
Uncaught SyntaxError: Unexpected token :
I believe it may be because I'm getting back json, but trying to use jsonp. Here's what I'm trying to send:
$(function(){
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi"
},
success: function(data){
console.log(data);
},
});
});
I get a 200 OK response, and the data but still the above error (which I don't understand and would like to know more about)
Tumblr also kindly points out the following, but I'm unclear on the specifics.
All requests made with HTTP GET are JSONP-enabled. To use JSONP,
append jsonp= and the name of your callback function to the request.
JSONP requests will always return an HTTP status code of 200 but will
reflect the real status code in the meta field of the JSON response.
Any help would be awesome, thanks!

Do what Tumblr is telling you to - add a callback function name to the request
myJsonpCallback = function(data)
{
console.log(data);
}
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi",
jsonp : "myJsonpCallback"
}
});
========================================================
EDIT: The console.log thing is a syntax error since I didn't actually test this code.
What happens to success? I don't really know. Try and find out :) It will probably be called but data parameter likely be null or something.
The issue here is that jQuery names it's callback parameter callback, where as Tumblr is expecting jsonp. Upon 200 response jQuery likely simply eval()s the response, which is why myJsonpCallback is actually called.

In case you don't want to use jQuery:
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/{blog.tumblr.com}/posts?api_key={your api key}&jsonp=callback");
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
function callback(data){
console.log(data);
}
I've created simple function for this purpose:
function jsonpRequest(opt){
var params = "";
var blogName = "{your blog name}";
var api_key = "{api key}";
if("selector" in opt){params = "id=" + opt.selector;}
if(("offset" in opt) && ("limit" in opt)){params = "limit=" + opt.limit + "&offset=" + opt.offset;}
if("callback" in opt){params += "&jsonp=" + opt.callback;}else{params += "&jsonp=callback";}
params += "&api_key=" + api_key;
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/" + blogName + "/posts?" + params);
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
}
How to use it:
jsonpRequest({offset: 50, limit: 5});
function callback(data){do stuff here ...}
Alternative usage:
jsonpRequest({offset: 50, limit: 5, callback: "nameOfMyAmazingCallbackFunction"});
function nameOfMyAmazingCallbackFunction(data){do stuff here ...}

Related

Ajax call results in 500 {internal server error}

I am trying to send json data through ajax call.
Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.
var filters =
{
"a" : a_filters,
"b" : b_filters,
"c" : c_filters,
"d" : d_filters
};
$.ajax({
url : "query/get-filtered-data",
dataType : 'json',
async: "true",
data:JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
success : function(data){
},
failure: function(data){
alert('got an error');
}
});
EDIT : This is my server-side code.
var express = require('express');
var router = express.Router();
//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {
console.log(req);
var filters = JSON.parse(req.body);
console.log("foo");
var a_filters = filters["a"];
var b_filters = filters["b"];
var c_filters = filters["c"];
var d_filters = filters["d"];
res.send(query);
});
conosle.log('foo') doesn't print anything.
console.log(req) has req.body empty.
Thanks a lot in advance.
Because you are referencing req.body, you need to use a router method that includes a body - post or put.
You may also need to include type: "POST" in your jQuery Ajax method.
There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.

How to use Angular service in place of Ajax url property

Here is code:
loader:function(param,success,error){
$.ajax({
//url: 'http://localhost/mvcController?assetid=1&dataformat=attribute',
url: assetsMVCService.execute("mvcController", { assetId: 1, dataFormat: 'attribute' }),
dataType: 'text',
type: 'post',
success: function (data) {
alert('ok');
},
error: function () {
error.apply(this, arguments);
}
});
assetsMVCService is my wrapper for Angular service. Unfortunately, a product that I am implementing forces me to use AJAX call to get data. Normally, I would use services to get data and then scope for data binding. Is it possible to use a service assigned to the url property in the code above? Interesting enough, I am hitting server with the code above. But something gets wrong on the server.
Thanks
Yes. You could do something like this:
app.service('MVC', function($http) {
var root = 'http://localhost/mvcController';
var queryParams = '?assetid=1&dataformat=attribute';
this.get = function(num) {
return $http.get(root + '/' + num + queryParams);
};
// or if you want to pass the query params in
this.execute = function(assetId, dataFormat) {
return $http.get(root + '?assetId=' + assetId + '&dataFormat=' + dataFormat;
};
// other routes
});
Note that $http can and should be used instead of $.ajax when you're using Angular. It does pretty much the same thing as $.ajax, except it plays nice with Angular.

406 Error when returning JSON object – Unexpected content

A few colleagues and I have a problem whereby the response from an ajax call returns some unexpected content. Rather than getting a simple JSON object back with various properties, the value of result.responseText is the HTML markup of a generic 406 status error page, saying the MIME type is not accepted by the browser.
The call is made like so:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('.promotion_banner .loader').hide();
$('.promotion_banner').html(result);
},
error: function (result) {
var obj = result.responseText;
if (obj.isRedirect) {
document.location = obj.redirectUrl;
}
else {
$('.promotion_banner .loader').hide();
$(".error-wrapper").removeClass("hidden");
var generic_error = document.getElementById('generic_error').value;
$(".error-wrapper p").html(generic_error);
}
},
beforeSend: function() {
$('.promotion_banner .loader').show();
}
});
The controller response to the call is like so:
Response.StatusCode = (int)HttpStatusCode.NotAcceptable; // 406
return Json(new { errorMessage = LocalErrorMessages.Website_Promotions_FreeFiver_General_Problem, isRedirect = false } );
We would expect result.responseText to contain key values for errorMessage and isRedirect, but they’re not there.
It’s worth pointing out that this code is multi-tenanted, shared by the current application and another one, where it works absolutely fine.
We’ve tried:
- Configuring IIS to show detailed error responses rather than a custom page for more detail – gives us nothing extra towards solving the problem.
- Allowing all response content types to the call
- Changing the culture of our site (which is currently es-ES)
- Various web.config tweaks
Has anyone ever had this problem?
Simplify your request. Maybe something like:
$.ajax({
url: '/promociones/cincogratis/canjear-codigo-promocional',
type: 'GET',
data: {foo:'bar', one:'two'},
dataType: 'json',
success: function (result) {
console.dir(result);
},
error: function (xhr) {
console.dir(xhr)
}
});
And post the response from the server. This kind of error seems a request problem rather than server configuration issue

How to call Twitter v1.1 API in javascript using AJAX

Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.

jQuery Ajax Get Doesn't Pass Received Data Into Success Function at Internet Explorer

My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).

Resources