JavaScript: using AJAX URLs

One of the major causes of failure during AJAX requests is the poor understanding of how AJAX URLs work. In fact, many times browsers will return an error saying that you don't have the necessary privileges on a given resource. This is due to the fact that your AJAX URLs are not properly constructed. The first thing you need to understand is that URLs can be either relative or absolute. As a rule of thumb, you should always use absolute URLs on your web sites.

The problem with this solution is that the path to your server-side script may change depending on where you're running your requests. A quick solution is to set your AJAX URLs by using a default path, like this:


var Ajax = {

    baseURL: document.domain,
    basePath: '/ajax/process.php',
    ajaxURL: 'http://' + this.baseURL + this.basePath,
    runRequest: function() {
    
    
       // use your AJAX URL here
    
    }
};

This is a basic path, without parameters to be passed along with the URL. When using URLs with parameters, you should always encode special characters using one of the built-in JavaScript functions, like these. However, parameters change depending on whether you're using GET or POST requests. You can programmatically retrieve such parameters in this way:

var Ajax = {

    baseURL: document.domain,
    basePath: '/ajax/process.php',
    ajaxURL: 'http://' + this.baseURL + this.basePath,
    getFormData: function(formElement) {
    
      formElement = document.getElementById(formElement) || document.forms[0];
      
      var inputs = formElement.getElementsByTagName('input');
      
      var i, len = inputs.length, params = '';
      
      for(i = 0; i < len; i += 1) {
      
      
          var input = inputs[i];
          var type = input.getAttribute('type');
          var name = input.getAttribute('name');
          var value = input.value;
          
          if(type != 'submit' || type != 'button') {
          
          
              params += '&' + name + '=' + value;
          
          
          }
      
      
      }
      
      return params;
      
    
    },
    
    runRequest: function() {
    
    
       // use your AJAX URL here with parameters
       
       var parameters = this.getFormData('test');
       
       var fullURL = this.ajaxURL + '?' + parameters;
    
    }
};

Of course, before sending your request you should encode all special characters, as explained earlier.

2 thoughts on “JavaScript: using AJAX URLs”

Leave a Reply

Note: Only a member of this blog may post a comment.