Thursday, March 21, 2013

Ajax Problem in IE

I am sharing an Ajax problem that I had faced earlier with IE. Check the following Javascript code out.

<script>
var site_url = "http://example.com/";
// A function which fetches content thru Ajax
function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  site_url + "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) 

        {
            jQuery('#'+target_elem).html(response);
        }
    });
}
//// Function ends here

</script> 

Very simple code; its purpose is to call ajax.php, get the response and place the response in a target element. Problem was it was not running on IE. Even though it ran perfectly on local Xampp installation, it severely failed when ran from an online server.

The problem was with the "url" parameter in the Ajax call, which has "http://" in it. This made the whole Ajax calling process fail. Probably IE assumes that it is a cross-domain ajax call.

Rewriting the function following way fixed this issue.

function load_cities_for_state(statename, target_elem)
{
  jQuery.ajax({
        url:  "ajax.php",
        type: 'POST',
        data: "load_city_for_state=1&state_name=" + statename,
        success: function(response) {
          jQuery('#'+target_elem).html(response);
        }
    });
}


But this won't be a solution when you use custom URL in your website i.e http://www.findpeople.com/state/CA/city/San_Jose. Calling "ajax.php" would mean the path of the said file is  http://www.findpeople.com/state/CA/city/San_Jose/ajax.php which is wrong. The solution to it would be to declare a <base> tag in the header of your website as shown in the line below.

<base href='http://www.findpeople.com/' />

Mentioning a base URL for all the pages of your site, calling "ajax.php" through Ajax would always give "http://www.findpeople.com/ajax.php" as server URL.

No comments: