How to extract data from Tumblr API (JSON)? - json

I have set up a Tumblr account and registered my application to authenticate it.
Tumblr Documentation: http://www.tumblr.com/docs/en/api/v2
I understand the API outputs JSON like this:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": {
"title": "David's Log",
"posts": 3456,
"name": "david",
"url": "http:\/\/david.tumblr.com\/",
"updated": 1308953007,
"description": "<p><strong>Mr. Karp<\/strong> is tall and skinny, with
unflinching blue eyes a mop of brown hair.\r\n
"ask": true,
"ask_anon": false,
"likes": 12345
}
}
}
Thats fine, but the documentation ends there. I have no idea how to get this information and display it on my site.
I thought the way you would get it would be something like:
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api-key=myapikey",
dataType: 'jsonp',
success: function(results){
console.log(results);
}
});
But this does nothing.
Can anyone help me out? Thanks

results is now the object you can use to reference the JSON structure. When you console.log the results object, it should appear in the Javascript developer console where you can explore the object tree.
The response object
So when your success callback receives the response, the following should be available to you:
results.meta.status => 200
results.meta.msg => "OK"
results.response.title => "David's Log"
results.response.posts => 3456
results.response.name => "david"
results.response.url => "http://david.tumblr.com/"
results.response.updated => 1308953007
results.response.description => "<p><strong>Mr. Karp</strong>.."
results.response.ask => true
results.response.ask_anon => false
results.response.likes => 12345
Writing to the page
If you actually want to see something written to your page you'll need to use a function that modifies the DOM such as document.write, or, since you're using Jquery, $("#myDivId").html(results.response.title);
Try this:
Add <div id="myDivId"></div> somewhere in the of your page, and
Add $("#myDivId").html(results.response.title); in your success callback function
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api_key=myapikey",
dataType: 'jsonp',
success: function(results){
// Logs to your javascript console.
console.log(results);
// writes the title to a div with the Id "myDivId" (ie. <div id="myDivId"></div>)
$("#myDivId").html(results.response.title);
}
});

In the question code, the request type was not being set and it was being rejected by tumblr. The jsonp error response was printing-out. The code below correctly makes the jsonp request.
The key was specifying the type, and the dataType. Good Luck happy hacking. ;-)
$.ajax({
type:'GET',
url: "http://api.tumblr.com/v2/blog/jdavidnet.tumblr.com/info",
dataType:'jsonp',
data: {
api_key : "myapikey"
},
success:function(response){
console.log(response, arguments);
}
});

One way to write an object to the screen is to add an element containing its JSON representation to the page:
$.ajax({
url: "http://api.tumblr.com/v2/blog/myblog.tumblr.com/info?api-key=myapikey",
dataType: 'jsonp',
success: function(results){
$("body").append(
$("<pre/>").text(JSON.stringify(results, null, " "))
);
}
});
Here is a demonstration: http://jsfiddle.net/MZR2Z/1/

Related

Raw json is not appearing on the page

I am trying to do a 'get' request through ajax on a url. everything works fine on the console but unable to get the raw json data to display on the page. here data.collections gives me an array of objects. I specifically want raw json data only on the page.
my script is this:
var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
});
$('.rsh').html(research);
html is this
<div class = 'rsh'></div>
I want raw json data on page like this but my page is blank.
{
"lab": {
"type": "xy",
"year": "yz",
"team": "yx"
},
"name": "qwerty",
"assistants": 5,
}
edit: this question deals with displaying data in raw json format on the page. Unfortunately the problem in my code was wrong placement of the code. Initial question has nothing to do with asynchronous nature although it is good to know.
var research;
$.ajax({
url: url,
type: 'GET',
dataType: 'json'})
.done(function(data){
research= JSON.stringfy(data.collections)
$('.rsh').html(research);
});
An ajax call is asynchronous so you will need to use the response within the done/success method.

Post Raw Json via .submit()

How can I post username/password as Raw JSON via form.submit().
loginForm.submit({
url: 'localhost/login',
method: 'post',
jsonData: loginForm.getValues()
...
success: ...
even with Ext.JSON.encode(loginForm.getValues()) server is receiving as username=test&password=test which I need to be {"username":"test","password":"test"}
You should probably try something like
Ext.Ajax.request({
method: 'POST',
url: 'submit.php',
params : {
data: Ext.encode(loginForm.getValues())
},
success: function() {
},
failure: function() {
}
});
Source for reference
As is often the case with ExtJS, there's an easy answer. In the config of the loginForm:
Ext.create('Ext.form.Panel', {
title: 'Simple Form',
// The form will submit an AJAX request to this URL when submitted
url: 'save-form.php',
.... (blah blah blah)
jsonSubmit: true // <---- set this to TRUE
});
Set the property jsonSubmit: true. Then when you use loginForm.submit(), your object will be submitted as JSON rather than form params.
Here's a link to the form docs:
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.form.Panel
When a form is submitted, it is not submitted in JSON format.
In order to submit JSON string, Ext.Ajax.request must be used.
http://www.sencha.com/forum/showthread.php?132082-jsonData-in-submit-action-of-form
I just had to change
loginForm.submit({})
to
Ext.Ajax.request({})
and use
params: Ext.JSON.encode(loginForm.getValues()),
Bad DOCS.

jQuery ajax callback json parsing issue

I'm working with Github API V3
I'm using following code to make ajax call
$.ajax({
type:'POST',
url: 'https://api.github.com/gists',
data: JSON.stringify({
"public": true,
"files": {
"sample.html": {
"content": 'html content'
}
},
}),
success:function(response){
alert(response.id);
}
});
I have to stringify data as Github API returns Error 400! if i don't. With above example, Github API does response as I expect.
I'm having issue with callback parsing though. Above code works with webkit & opera but firefox fails with success function. I have to modify code as below to get work in firefox.
success:function(response){
alert(JSON.parse(response).id);
}
But then Webkit & Opera fails with success response with above modified code.
What is correct way to get success callback across all browser ? What I'm doing wrong ?
Add dataType: 'json', property to your ajax call check if it works..like the one below
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});

Solr live search using ExtJs4

i'm using solr+haystack(django plugin) on the backend and the search is working fine;
While Django(and Haystack) with its templates is doing everything for me(I mean its pretty simple to configure and use), ExtJS4 is a little more complex;
The question is how to use Solr using ExtJS4?
An example is very much appreciated;
Thanks for any help and sorry for my English;
As ExtJS4 is a MVC framework, the solution is done like MVC;
The controller/Search.js
Ext.define('yourapp.controller.Search',{
extend:'Ext.app.Controller',
stores:[
'Searches'
],
views:[
'search.Search',
'search.SearchList'
],
models:[
'Search'
],
init:function(){
this.control({
"search":{
'keyup':this.search,
},
});
},
search:function(inputedTxt, e, eOpts){
this.getSearchesStore().load({
//When sending a request, q will rely to request.POST['q'] on server-side;
//inputedTxt.getValue() -- a value, entered in textfield (or whatever)
params:{
q:inputedTxt.getValue()
},
callback:function(result){
if(result[0]){
//do something with the result
//i'd been creating a window with a grid inside. "Grid"'s view is written below.
}
}
}
});
The models/Search.js
Ext.define('yourapp.model.Search',{
extend:'Ext.data.Model',
fields:[
{name:'name', type:'string'}
]
});
The store/Searches.js
Ext.define('yourapp.store.Searches',{
extend:'Ext.data.Store',
storeId: "searchStore",
model:'yourapp.model.Search',
autoLoad: false,
proxy:{
type:'ajax',
// server-side url
url: '/searchlist/',
actionMethods:{create: "POST", read: "POST", update: "POST", destroy: "POST"},
reader:{
type:'json',
root:'searches'
}
}
});
The view/search/Search.js
//a Text field to input text;
Ext.define('yourapp.view.search.Search',{
extend:'Ext.form.field.Text',
alias: 'widget.search',
id: "searchView",
enableKeyEvents: true,
initComponent:function(){
this.callParent(arguments);
}
});
The view/search/SearchList.js
//a view for a result
Ext.define('yourapp.view.search.SearchList',{
extend: 'Ext.grid.Panel',
alias:'widget.searchlist',
title: 'search result',
store: 'Searches',
columns:[
{
header:'Name',
dataIndex:'name',
flex:1
}
]
});
Somewhere in the view/Viewport.js xtype: 'search', should be inserted for a text field to be displayed.
That's all for a ExtJS4 part.
On server-side -- Django:
'haystack' and Solr should be installed and configured (by 'configured' i mean: search should already work on the server-side);
In someapp/view.py
def searchlist(request):
from haystack.query import SearchQuerySet
# POST["q"] should be receivedt from our client-side
searchText = request.POST["q"]
sqs = SearchQuerySet().filter(name=searchText)
data = []
for result in sqs:
data.append({"name": result.object.name})
return HttpResponse('{ success:true, searches:'+simplejson.dumps(data)+'}', mimetype = 'application/json')
Finally in your urls.py you should add:
(r'^searchlist/','someapp.views.searchlist'),
That was for it. Best wishes.
P.S.
I know this is not the greatest answer and there's lack of explanation, but as for me, I rather prefer a code example than verbal explanation.
SOLR has JSON output from its queries using wt=json param and can readily be consumed by ExtJS.
http://wiki.apache.org/solr/SolJSON?action=fullsearch&context=180&value=jsonp&titlesearch=Titles#JSON_Response_Writer
if you need to use jsonp you can specify a callback function via this param json.wrf=callback

Getting invalid json primitive error in jquery-ajax

I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.
The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }
I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.