Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 836
Alexey Zakharov Avatar asked Jul 18 '11 04:07

Alexey Zakharov


People also ask

Can I make AJAX requests by jQuery?

jQuery ajax() Method. The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.

Which jQuery method is used to send a request to the API URL?

The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.

What goes in URL of AJAX?

The $. ajax() Function. The url parameter is a string containing the URL you want to reach with the Ajax call, while settings is an object literal containing the configuration for the Ajax request. In its first form, this function performs an Ajax request using the url parameter and the options specified in settings .


2 Answers

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;
    }
})
like image 150
Matt Sgarlata Avatar answered Oct 20 '22 13:10

Matt Sgarlata


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;
     }
  }
});
like image 34
Sumit Wadhwa Avatar answered Oct 20 '22 11:10

Sumit Wadhwa