Careers | Blog | Sitemap  
   
   
  Wanna try working with us?  
  email: info@hibiscustech.com  
     
 

Posts Tagged ‘AJAX’

Dynamic Javascript and Cross Domain AJAX

Friday, November 13th, 2009

For those of you who’ve been frustrated by the XMLHTTPRequest object’s inability to make cross domain requests, there is a way out. This method does away with the XMLHTTPRequest object and uses a technique called dynamic javascript. Here’s how it works.

You would normally define a script tag something like this:

What if you replaced it with this piece of code?

But that can’t possibly work right? The browser will know right away that something’s off, right? Actually your browser won’t find out if your backend script (yourscript.php here) returns what it expects - Javascript code. There are two things you need to do with your backend script to achieve this. First you put in a header that tells the browser that the data returned is of type javascript.

This effectively fools the browser into thinking it’s reading a .js file. From then on print all the javascript statements you want wrapped within php strings. You will do something like -

That’s it! Try it out. Put the script tag in an HTML page, and the php file on the server, and on opening the page in the browser you should be able to see the dialog box. Of course this simple example does not convey the true power of this technique - that you can make database calls in the script and modify the javascript accordingly.

Suppose you have three clickable images on the screen. Each time one of them is clicked, you have to go back to the database, pick up a message associated with that image and display it. How would you do it? One solution would be to prepopulate hidden divs or javascript variables in the page using a server side scripting language. This idea immediately fails if you do not have control over the web page’s preprocessing. Perhaps you are only supplying a piece of javascript that ‘decorates’ the existing page with the required message, without assuming anything about the content. Then you have to make database calls on your server through the only entry point available to you: the javascript code.

A sample code would look something like this:

This function creates a script tag on clicking the image and that script tag calls a php file that returns the content. First it checks that a dynamically created script tag designed to do precisely this does not already exist. A large number of clicks would create a large number of script tags and that would not do site performance any good. What will the backend php code look like?

There you go, simple and powerful. A combination of dynamic script creation and .js file imitation using a server side script can, to a certain extent, simulate the AJAX effect of updating parts of a page without a complete refresh.


  Home | About Us | Products | Portfolio | Work with us | Careers | Blog | Sitemap