Archive

Archive for September, 2011

Single Image from Flikr using API in AJAX

September 22, 2011 Leave a comment

Here is a code example of how to get one single image out of Flikr, and place it into a html page using AJAX.

Just call getImageFromFlikr with the search text, and an output element. It works asynchronously, so it will return as soon as Flikr is contacted.

function getImageFromFlikr(searchText, output)
{
try
{
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState!=4) return;
if (xmlhttp.status != 200)
{
output.innerHTML = “Error”;
}
if (xmlhttp.status == 200)
{
output.innerHTML = eval(xmlhttp.responseText); //retrieve result as an JavaScript object
}
}
var strUrl = “http://api.flickr.com/services/rest/?”;
strUrl += “method=flickr.photos.search”;
strUrl += “&api_key=cabbc1b68c18461ca0627991833d8f97”;
strUrl += “&text=” + encodeURIComponent(searchText);
strUrl += “&per_page=1”;
strUrl += “&format=json”;
strUrl += “&sort=relevance”;
xmlhttp.open(“GET”,strUrl,true);
xmlhttp.open(“GET”,strUrl,true);
xmlhttp.send();
}
catch (err)
{
output.innerHTML = err.message;
}
}

function jsonFlickrApi(flikrObj)
{
var fmt=”http://farm{farm-id}.static.flickr.com/{server-id}/{id}_{secret}_m.jpg”;
fmt = fmt.replace(“{farm-id}”,flikrObj.photos.photo[0].farm);
fmt = fmt.replace(“{server-id}”,flikrObj.photos.photo[0].server);
fmt = fmt.replace(“{id}”,flikrObj.photos.photo[0].id);
fmt = fmt.replace(“{secret}”,flikrObj.photos.photo[0].secret);
var html = “<img src='” + fmt + “‘>”;
return html;
}

Categories: Uncategorized

Find Backlinks to a website using AJAX

September 9, 2011 Leave a comment

 One of the most basic SEO tools is a backlink checker, and if you need to fine tune this, then automating the check will save you lots of time, so this is my experience with the SEOMOZ links API  using AJAX.

The basis of the API, is a call to the URL: http://lsapi.seomoz.com/linkscape/links/<URL>?Scope=page_to_page&Sort=page_authority where <URL>  is the site in question. This throws up the basic HTTP authentication challenge, so I’ve included the username and password:
Your Access ID: member-2dd03f462e
Your Secret Key: 018a47ae0940f6342577b24dfce80a5f

This code requires the Base64.js code library from www.webtoolkit.info, to base64 encode the HTTP authentication. Note that this code will only work when run locally from Internet Explorer, it won’t work hosted online due to cross-domain restrictions.

  <input type="text" name="input" id="input" value="www.xyz.com">
  <input type="button" onclick="BacklinkCheck()" value="Check">
  <br>
  <div id="output"></div>
  <script language="javascript">
   function BacklinkCheck()
   {
	    var auth = authenticate('member-2dd03f462e','018a47ae0940f6342577b24dfce80a5f');
		var input = document.getElementById("input");
		var output  = document.getElementById("output");
		output.innerHTML = "working...";
		var http=new XMLHttpRequest();
		var url = "http://lsapi.seomoz.com/linkscape/links/"
		url += input.value + "?Scope=page_to_page&Sort=page_authority";
		http.open("GET", url, true);
		http.setRequestHeader('Authorization', auth);
		http.setRequestHeader('Content-type', 'text/html; charset=unicode');
		http.onreadystatechange = function() {//Call a function when the state changes.
			if(http.readyState == 4 && http.status == 200) {
				 var html = "<table>"
				 var jsondata=eval("("+http.responseText+")");
				 jsondata = jsondata.sort(
					function(a, b){
					 if (a.upl < b.upl) //sort string ascending
					  return -1
					 if (a.upl > b.upl)
					  return 1
					 return 0 //default return value (no sorting)
				   });
				  for (i in jsondata )
				 {
					var backlink = jsondata[i];
					if (i % 2 == 0)
					{
						html += "<tr>"
					}
					else
					{
						html += "<tr>"
					}
html += "<td width=50%><a onclick=\"this.innerHTML='" + backlink.uu.replace('\'','') + "'\">"+ backlink.upl + "</a></td>";
html += "<td width=50%>" + backlink.ut + "</td>";
html += "</tr>";
}
html += "</table>";
output.innerHTML = html;
}
if(http.readyState == 4 && http.status != 200)
{
alert("Something went wrong");
}
}
http.send(null);
}

function authenticate(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
</script>
Categories: Uncategorized

Convert text to a HTML table

September 7, 2011 Leave a comment

 Here is a handy litte script that converts tabulated text into a HTML table. Apply a CSS stylesheet to it, and it’ll look nice too …

  <textarea id="input" cols=100 rows=10>
  </textarea><br>
  <input type="button" id="Tabelize" onclick="tabilize()" value="tabilize">
  <div id="output"></div>

<script language="javascript">
 function tabilize()
 {
	var input = document.getElementById("input");
	var output = document.getElementById("output");	
	var splitInput = input.value.split("\n");
	var html = "<table>";
	for(i in splitInput)
	{
	   if (i % 2 == 0)
	   {
			html += "<tr>";
	   }
	   else
	   {
	        html += "<tr>";
	   }
	   var splitRow = splitInput[i].split("\t");
	   for(j in splitRow)
	   {
	     html += "<td>" + splitRow[j] + "</td>";
	   }
       html += "</tr>";
	}
    html += "</table>";
	html = html.replace(/</g,"&lt;");
    html = html.replace(/>/g,"&gt;"); 
	output.innerHTML = html;
 }
</script>
Categories: Uncategorized

Open Source Pastebin in .NET

September 3, 2011 1 comment

A pastebin is designed to be an easy way to quickly post some text online, so that others can see it. It also has applications in cross-firewall data traversal, where one peer can upload data to a pastebin, and the other peer can poll the pastebin for the message to arrive.  This was the kind of pastebin I was after.

I looked at pastebin.com and paste.kde.org, to see if they were suitable. Paste.kde.org seemed promising,  where you could paste easily, using a URL like this:

http://paste.kde.org/?paste_data=Hello+World&paste_lang=c&api_submit=true&mode=xml&paste_project=fiachspastebin

Which would return an ID, which you could retrieve using http://paste.kde.org/api/xml/117613, for example. The problem came, when I wanted to list all pastes by a particular user, or project, and I spotted that it wasn’t working as expected, like http://paste.kde.org/~fiachspastebin/api/xml/all/ seemed to return numerous pastes by other users.

So, I decided to write my own pastebin, which would store the messages in-memory. This meant that they would be deleted as the IIS worker process recycled, but, I didn’t need longevity.

Using two simple actions “action=update” which either created or updated a paste, and assigned it to a “user“, containing the text contained in the “text” querystring parameter. Then when “action=get” then the text associated with that “user” would be returned.

So, to store text with a user, you simply call:

http://url/pastebin.aspx?action=update&user=dananos&text=Hello+World

Then to retrieve that text you call

http://url/pastebin.aspx?action=get&user=dananos

And that’s it. The code I used is below:

  public static Hashtable data = new Hashtable();
    protected void Page_Load(object sender, EventArgs e)
    {
        string action = Request.QueryString["Action"];
        string user = Request.QueryString["User"];
        string text = Request.QueryString["Text"];
        if (string.IsNullOrEmpty(action) || string.IsNullOrEmpty(user))
        {
            Response.Write("Action and User is required");
            return;
        }
        if (action == "update")
        {
            PasteBin.data[user] = text;
            Response.Write("OK");
        }
        if (action == "get")
        {
            if (PasteBin.data.ContainsKey(user))
            {
                Response.Write(PasteBin.data[user]);
            }
            else
            {
                Response.Write("NO DATA");
            }
        }
    }

I’ve ported the same code to PHP, for Linux users. This code requires the $_APP library, which is posted at http://www.leosingleton.com/projects/code/phpapp/

This is hosted at http://pastebin.omadataobjects.com/bin.php

<?php
include("app.php");
application_start();
$action = $_REQUEST["action"];
$user = $_REQUEST["user"];
$text = $_REQUEST["text"];
if ($action == "" || $user == "")
{
   echo("action and user is required");
}
else
{
   if ($action=="update")
   {
	$_APP[$user] = $text;
	echo "OK";
   }
   if ($action=="get")
   {
	echo stripslashes($_APP[$user]);
   }
}
application_end();
?>
Categories: Uncategorized