AJAX requests in web site template

June 18, 2006 / Filed under: JavaScript, Web Development, XML

JavaScript let’s you send data with the xmlhttprequest object, using a full-length URL, such as this:

mypage.php?today=Sunday&sky=blue&weather=80

You’ll recognize this URL from any development work you do - it simply contains variables that are passed from one page, to the next.

With JavaScript, you can request this URL, which then connects to the server, and runs through any processes on that page (mypage.php).

However, if your web site is set up as a template (possibly with mod_rewrite, which could redirect every request to one page), you may have an issue with this.

A template means that you have one page that contains the static HTML, such as <head> tags, <body> tags, and possibly the DOCTYPE, and other stuff that doesn’t change - or, at least, is consistent amongst all pages in your web site.

Every page requested on your site uses that template page, and simply fills in the content, based on the request.

This is a very good way to setup a web site, but you may run into problems when using AJAX.

Any AJAX requests (within your site template) will have the HTML tags surrounding the XML.

So, you’ll have something like this:

<html>

    <head>

    </head>

    <body>
        
        <responseXML>
            <result>Query result</result>
        </responseXML>

    </body>

</html>

An XML file (a valid XML file) can’t (and shouldn’t) have all the HTML included in it. This makes parsing it much more cumbersome, and it’s just not the right way to do it.

To get around this, you’ll need to request a file that’s not part of your template structure.

I’m open to ideas on this.

The only quick thing I can think of is requesting a file that’s off the server - possibly another domain, which could "house" AJAX request pages. This is probably not the best approach, since if that site goes down for some reason, all other sites are affected.

Comments/Mentions

# Jennifer Grucza at 6/20/2006 8:21 am cst

Well it depends on how your template system works. Can’t you tell it to only work on certain files or folders or filename patterns? Or to exclude certain ones? So that not everything goes through the template. E.g. put your AJAX pages into a different folder and exclude them.

# Matthom at 6/20/2006 11:37 am cst

Yes. In fact, every request that does actually exist as a path (ie: mydomain.com/documents/expenses.doc) should be reached. In other words, if the file or folder does not exist, it goes to my default template page.

So I could easily just request (through AJAX) the full file path, but there’s one problem: appending variables to that file path. Once you use the question mark (?) in the file path (through AJAX), it breaks.

Not sure if this is part of the .htaccess file, that’s not allowing it, or what. Still trying to figure it out.