| Creating CCIT Posted by: Jordan in SQL, PHP, AJAX on May 26, 2008 |
CCIT (CodeCall Inline Text) is an inline text link system similar to the inline text ads you see on the CodeCall Forum. The goal is to fetch programming terms from the Wiki and display a brief description of the term in a small JavaScript popup. The reason JavaScript was choosen is to make the application portable for other webmasters. CCIT can be added to any website by entering one HTML script tag.
How does it work?
The concept is simple:
- User visits a page
- CCIT JavaScript is executed
- All text is grabbed from the page. Alternatively div tags can be used to specify which text CCIT uses
- At this stage several functions are ran to parse the text. All words are converted into lowercase. Common words are removed. HTML is removed. Duplicates are removed.
- The text is passed to a PHP script using AJAX
- A SQL query is executed that determines which words of the passed text is are in the CodeCall Wiki.
- An XML result is returned containing all, if any, words that are in the Wiki
- CCIT JavaScript highlights and links the keywords found
So far I have completed all of these steps. The only thing remaining is the popup JavaScript window.
Why choose this method?
I didn't really see any other alternative than to use AJAX for connecting to the server database. Since JavaScript is client side only there is no chance to read the database directly at execution or even read a file. I viewed the code of several other inline text ad system and they seem convoluted.
Code Snippets
To cycle through all div tags containing a certain ID ("ccit" in this case) in JavaScript and return the HTML contents:
//**********************************
// This loops through all div tags with the
// ccit ID and extracts the HTML.
//**********************************
function getHTML() {
var divCollection = document.getElementsByTagName("div");
var htmlContent="";
for (var i=0; i < divCollection.length; i++) {
if(divCollection[i].getAttribute("id") == "ccit") {
htmlContent += divCollection[i].innerHTML;
}
}
return htmlContent;
}
Remove all punctuation:
myString = myString.replace(/W/g, ' ');
Remove duplicate words from space delimited string:
//**********************************
// Remove duplicate words
//**********************************
function removeDuplicate(content) {
var arrContent = content.split(" ");
var arrNewContent = [];
var seenWords = [];
for (var i=0; i
{
if (!seenWords[arrContent[i]])
{
seenWords[arrContent[i]] = true;
arrNewContent.push(arrContent[i]);
}
}
return arrNewContent.join(" ");
}