Recent Posts
- 10 Things To Do When Launching A Site
- Using PHP to connect to SFTP
- Asynchronous Virtual Pageviews with Google Analytics
- 5 Advanced Text Editing Keyboard Shortcuts
- Get the headers of a HTTP request with PHP
- How-to: Create PDF preview images in PHP – Part 2
- How-to: Create PDF preview images in PHP
- Quick Code: Get the domain name in JS
- Things to think about when designing a logo
- Javascript Array Functions
Topics
Quick Code: Get the domain name in JS
Posted on 10th June 2009 by Jacob Wyke
When your developing a site or online application that uses a lot of XML HTTP Requests (XHR) it’s generally a good idea to use a full URL when creating a request. If you then try to re-use your code across multiple sites and domains, you will find you get errors due to posting to a different domain than the current site.
Solving this problem is easy and will make your Javascript (JS) code more re-usable and easier to manage. All you need to do is create a global variable at the start of your JS file to automagically get the sites domain so you can append it to all your XHR calls.
var DOMAIN = 'http://'+document.domain+'/';
Then just use this variable with all your XHR calls.
Easy!
Be the first to add your voice to this post!
Start the discussion and leave your views or thoughts by writing a comment using the form above.