Positionizer API-Calls using jQuery
Here is an example of how to make a Positionizer API Call using jQuery's cozy getJSON function. First of all, we need to include the jQuery library in the head-section of our website:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js">
Of course you can use your own copy of jQuery here, if you don't want to depend on Google. Next we set up a table with ID "myTable" in our body-section, that will get dynamically filled when the API-Call finishes:
<table id="myTable">
<thead>
<tr>
<th>Google Query</th>
<th>Positions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Alright, so now we're prepared for some jQuery-magic. Copy the following JavaScript-Code into your head-section:
$(document).ready(function(){
// base URL of positionizer's API
var request = "http://www.positionizer.com/positionize";
// url to look for, without "http://"
var url = "www.omsn.de";
var queries = ["omsn.de", "omsnize your world", "challenging reality"];
var engine = "google";
// put it all together, don't forget the callback-parameter
request = "?url=" url "&engine=" engine "&queries=" queries.join(",") "&callback=?"
$.getJSON(request, function(jsonObject){
for(query in jsonObject.google) {
var tr = $("<tr>");
tr.append( $("<td>").text(query) );
var positions = "";
for(pos in jsonObject.google[query]) {
positions = "<a href="" jsonObject.google[query][pos] "">" pos "</a> ";
}
tr.append( $("<td>").html(positions) );
$("#myTable").append(tr);
}
});
});
Let's take a look what happens here. First, we define the parameters for the API-call. url and queries are required, if they don't appear in the request, you'll get an error. The engine-parameter is optional, but we set it to receive only results from Google. And finally we put the parameters together to form an URL. The callback=? parameter is necessary to prevent access denial, caused by Firefox's security model. jQuery automatically replaces the "?" with an according callback-function.
Next we call the getJSON-function and pass the request string. Once the request is finished, the function we specified as second parameter gets called with an already valid JSON object as parameter.
We loop through jsonObject to get the results. For each query, we create a new table row. In the left column we write the queries and in the right one the linked positions. At the end of each query-loop, we append the created row dynamically to our table.
You can see a demo of it here. Enjoy using Positionizer's API!
Find me on