AJAX Call Function

December 1st, 2009 No comments »

I created this about a month ago for my ‘Designing for Server Side Languages’ class. I’ve always been a big fan of using jQuery, as it makes everything 10x simpler, but I think I enjoy writing plain old Javascript more. It also cuts down on load time quite a bit, as the jQuery.js file is getting bigger and bigger. The other requirement for the class project was that we had to use a lot of AJAX.

Now I don’t know how many people have actually used a library-less AJAX call, but it’s a good chunk of code. A simple HTTP Request that alerts a response runs about 20 lines of code. Since my application for class was going to have multiple AJAX calls on each page, I needed to add an AJAX method to my core.js file. After a couple of hours I got it perfected and it works flawlessly in Firefox, Safari, and IE7+ (haven’t checked any others). Here’s the code:


Core.ajax = function(method,variables,action,respFunct,respType)
{
    try
    {
        var requester = new XMLHttpRequest();
    } catch (error)
    {
        try
        {
            var requester = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (error)
        {
            var requester = null;
        }
    }
    if (requester == null)
    {
        alert('epic fail');
    } else
    {
        requester.onreadystatechange = function()
        {
            if (requester.readyState == 4)
            {
                if (requester.status == 200 || requester.status == 304)
                {
                    if(respType == 'XML')
                    {
                        var resp = requester.responseXML.documentElement;
                    }else
                    {
                        var resp = requester.responseText;
                    }
                    respFunct(resp);
                } else
                {
                    alert('epic fail');
                }
            }
        }

        var openVars = "";
        for(i in variables)
        {
            openVars = openVars + i + "=" + variables[i] + "&";
        }
        var temp = openVars.lastIndexOf("&");
        openVars = openVars.slice(0,temp);
        if(method == "GET")
        {
            reqOpen = "GET",action + "?" + openVars,true;
            requester.open("GET",action + "?" + openVars,true);
            requester.send(null);
        }else
        {
            requester.open("POST",action,true);
            var header = "Content-type","application/x-www-form-urlencoded";
            requester.setRequestHeader(header);
            requester.send(openVars);
        }
    }
}

The method passes 5 parameters:

  • Method: The method of data being sent (GET or POST)
  • Variables: An associative array of the data being sent
  • Action: PHP file that will process the request
  • Response Function: Function to be called when a successful response is returned from the PHP file (passes the response as a parameter)
  • Response Type: Determines whether the response will be in XML format or simple text (XML or false)

Here is an example of how you could call the AJAX method:

var vars = {
   first : 'James',
   last : 'Wilson',
   location : 'Dallas'
}
Core.ajax("POST",vars,"ajax_process.php",Site.sortResponse,"XML");

Site.sortResponse = function(resp)
{
	alert(resp);
}

Any thoughts would be much appreciated!

PHP Spellcheck Function

November 30th, 2009 No comments »

So I’ve been working on a lot of string manipulation on a project at work over the past month and came across a number of abbreviations coming from an external XML data feed. Since there are about 30,000 entries, I couldn’t go through and change each one manually, so I created a cool little PHP function that literally fixes mispelled words in strings.

function formatName($name,$abbreviations)
{
     $name = strtolower($name);
     $nameArray = explode(" ",$name);
     for($x=0 ; $x < count($nameArray) ; $x++)
     {
          if(array_key_exists($nameArray[$x],$abbreviations))
          {
               $keys = array_keys($abbreviations);
               $values = array_values($abbreviations);
               $index = array_search($nameArray[$x],$keys);
               for($i=0 ; $i < count($abbreviations) ; $i++)
               {
                    if($i == $index)
                    {
                         $nameArray[$x] = $values[$i];
                    }
               }
          }
     }
     $name = implode(" ",$nameArray);
     $name = ucwords($name);
     return $name;
}

The first parameter in the function ($name) is the string that needs to be checked for abbreviations. The second ($abbreviations) is an associative array containing common abbreviations as the keys and their full spellings as the values. Here is an example of what mine looked like:

$abbreviations = array(
     'trm' => 'trim',
     'bowhtr' => 'bowhunter',
     'explor' => 'explorer',
     'conv' => 'convertible',
     'htr' => 'hunter',
     'rev' => 'reversible',
     'ins' => 'insulated',
     'mck' => 'mock',
     'nat' => 'natural',
     'flintlck' => 'flintlock',
     'dbl' => 'double',
     'pkt' => 'pocket',
     'cmo' => 'camo',
     'bearclw' => 'bearclaw',
     'a/t' => 'all terrain',
     'allter' => 'all terrain',
     'mid-wt' => 'midweight',
     'midwght' => 'midweight',
     'hvywt' => 'heavyweight',
     'lgtwt' => 'lightweight',
     'wgt' => 'weight',
     'wght' => 'weight'
);

Pretty cool, huh? Let me know if there are any other ways it could be done or problems with the code.

Capstone Project

July 22nd, 2009 No comments »

It’s about that time to start work on the capstone project. Seeing how (as of now) I want to focus more in the PHP and AJAX area post-graduation, I think it would be fitting if I chose to do my capstone in those areas. After some intense brainstorming sessions, I’ve decided to create a social networking site.

Social networking is a pretty hit or miss part of the internet. You either create something that hasn’t been offered before in a great package and see it take off astronomically, or you fail at creating something new and find that you wasted months of development.  So the key is to find out what users want that hasn’t been created yet. Sounds easy, right?

Lets take a look at the pros and cons of the two most popular social networking sites on the web: Facebook and Myspace.

Facebook
Pros: Clutter-free, user friendly, loaded with features, fast loading, secure, very networked
Cons: Not much customizability, errors, have to watch what you put

Myspace
Pros: Very customizable, great for bands
Cons: Cluttered, ads everywhere, very long loads, lots of creepsters

One of the biggest problems I find with Facebook and Myspace is that family and employers can (and do) use it to keep tabs on people. This can be a big problem with young adults who want their social networking site to be a place where they can let loose and say what they want without having to face consequences. This is what my project will be based around. Users will have to register for it using a valid college or university email account, just like the original Facebook. This will keep all the unwanted traffic out.

The second feature my social networking site will have is a toned-down version of the myspace customizability. Much like Twitter, my site will allow basic font and background colors to be changed, as well as a background image. Users won’t be able to access the actual HTML or stylesheets of the webpage, so structure will stay static.

Some other features that I would like to see in my capstone project are:

  1. Chat
  2. Videos
  3. Audio playlists
  4. In-Depth profiles
  5. Blogging
  6. Status updates