There are several ways to communicate with the βforeignβ API. No need for ajax. Ajax is only for creating background calls in a template, triggering any event that you have in mind.
But let's say you want to chat with facebook GraphAPI to get a profile
http://graph.facebook.com/bill.clinton
The standard result is serialized as JSON, which is easily implemented in AJAX or any JavaScript library, hence the name JavaScript Object Notation.
So an example with AJAX could be:
function callFacebook() { $.ajax({ type: "GET", data: ({}), dataType: 'json', url: "http://graph.facebook.com/bill.clinton", success: function(data){ alert("Hi I am former "+data.name); } }); } callFacebook();
Include this in your javascript file or in your template between script tags, and you should get a nice message:
Hi i am former president bill clinton
Now you can include this warning in something more meaningful and put it in the h1 tag (you don't know why this makes sense)
$("body").html("<h1>"+data.name+"</h1>");
But sometimes you would like to get data and do something with it on the server side in your application.
Create django urlpattern and view, for example:
from urllib2 import urlopen from django.http import HttpResponse from django.utils import simplejson def call_bill(request): url = "http://graph.facebook.com/bill.clinton" json = urlopen(url).read()
Now go to your url
As a logical result, it is also quite possible to initiate asynchronous events through some user action. For example, the URL parameter in the previous ajax example could also be a django URL, such as "/ call_bill_clinton /".
<!-- add a button to call the function --> <button onclick="callFacebook();">Call Bill</button> function callFacebook() { $.ajax({ type: "GET", data: ({}), dataType: 'json', url: "/call_bill_clinton/", success: function(data){ alert("Hi I am former "+data.name+" and I came from Django"); } }); )
In addition, ajax calls allow you to do the same tricks as HTTP requests, you can use various request methods in combination with cool javascript events, for example, before the sendSend event
beforeSend: function() { $('#loading').show(); },
Where #loading might look something like this:
<div id="loading" style="display:none;"> <img src="{% static "images/loading.gif" %}" /> </div>