Alexey Zakharov
Alexey Zakharov

Reputation: 25112

What is the best way to set up base url for ajax request using Jquery?

Since phonegap is based on local html file it doesn't know about base url of remote server. I wonder what is the best way to set base url for ajax requests using jquery? Could anybody provide link to sample?

Currently i think about using jquery ajax prefilter.

Upvotes: 13

Views: 40739

Answers (5)

Sumit Wadhwa
Sumit Wadhwa

Reputation: 3217

You can also place a check to skip urls starting with http (probably cross-domain urls).

Make sure to place it right after including the jQuery file and before all ajax calls.

const baseUrl = 'http://example.com/sub/directory';

$.ajaxSetup({
  beforeSend: function(xhr, options) {
     if( options.url.indexOf('http') !== 0 ) {
        options.url = baseUrl + options.url;
     }
  }
});

Upvotes: 2

Sam S
Sam S

Reputation: 188

Remove leading slash to make ajax url relative to base defined in header.

<head>
    <base href="http://base.com/">
</head>
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        settings.url = settings.url.replace(/^\//,'')
    }
})

Upvotes: 4

Matt Sgarlata
Matt Sgarlata

Reputation: 1847

Both of the established answers have major drawbacks. Requiring a function to be called to massage your URL every time you make a request is a lot of extra typing. Adding a base tag to a page works great most of the time, but it causes some trouble if you're doing heavy duty work with SVGs. Here's a simple solution that fixes all your URLs at once without using the base tag.

var baseUrl = 'http://my.hardcoded.url/';
$.ajaxSetup({
    beforeSend: function(xhr, options) {
        options.url = baseUrl + options.url;
    }
})

Upvotes: 41

samy-delux
samy-delux

Reputation: 3069

The semantically correct way of doing this is to use the <base> tag:

<head>
    <base href="http://mydomain.com/">
</head>

Then retrieve the value like this (unfortunately jQuery.ajax() does not pick up this value automatically):

$('head base').attr('href');

Element reference: http://www.w3.org/TR/html4/struct/links.html#edef-BASE

Upvotes: 38

hayesgm
hayesgm

Reputation: 9096

When I dealt with this issue, I just put that information as a data-element on the tag.

 <body data-base="http://mydomain.com"> ...

And then used that in building out the proper URL for a given request:

 //If pathOrURL is a relative path (e.g. /users/1), then we return a qualified
 // URL, such as http://mydomain.com/users/1
 // otherwise, we return the URL as is
 var qualifyURL = function(pathOrURL) {
   if (!(new RegExp('^(http(s)?[:]//)','i')).test(pathOrURL)) {
     return $(document.body).data('base') + pathOrURL;
   }

   return pathOrURL;
 };

 //Use this helper function when calling $.ajax
 $.ajax({
   url: qualifyURL(url), ... });

This worked great for my experience with Phonegap. Hopefully this helps.

Upvotes: 16

Related Questions