1

I have a mobile ajax-rich website, that I want to put to phonegap to create "app". Website uses $.ajax extensivly, but to make it work inside pnonegap app, I have to declare domain in url settings.

Here is usual call, that I use now:

$.ajax({
    url: '/authentication/login',
    success: function(data){}
})

And here is what it supposed to look like to make it work inside an app:

$.ajax({
    url: 'http://my-domain.com/authentication/login',
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    success: function(data){}
})

As you can see, the only difference is that I have to set domain inline and I have to set header (that's needed for the backend).

I don't want to rewrite whole project and set domain in every ajax call, because it will prevent developent site call (when domain is localhost), so I wonder how do I modify $.ajax to rely on some GLOBALs - if e.g. SET_DOMAIN global is present, I want to add that domain name to each and every ajax call. Same with headers.

This way I will have to declare SET_DOMAIN and SET_HEADERS once, and can do it only in phonegap project, leaving regular website untouched.

Thanks in advance!

Denis Matafonov
  • 2,684
  • 23
  • 30
  • Can you not wrap this code inside of a method and then detect in that method if you are on dev or production? – rhughes Jan 31 '16 at 12:59
  • https://api.jquery.com/jquery.ajaxsetup/ is probably what you need, see also http://stackoverflow.com/questions/7686827/how-can-i-add-a-custom-http-header-to-ajax-request-with-js-or-jquery –  Jan 31 '16 at 13:01
  • looks like ajaxSetup is close to what I need, I'll if its possible to extend url, not override it – Denis Matafonov Jan 31 '16 at 13:16
  • @RC yep, ajaxSetup easily solved my problem post an answer, I'll accept `$.ajaxSetup({ beforeSend: function(xhr, settings) { settings.url = SET_DOMAIN + settings.url; } });` – Denis Matafonov Jan 31 '16 at 13:28
  • @ДенисМатафонов I just did point you in the right direction, you should post your working code as an answer and accept it ;) –  Jan 31 '16 at 13:56

1 Answers1

2

Thanks to @RC comment.

There is $.ajaxSetup function that can handle such things:

$.ajaxSetup(
 { beforeSend: function(xhr, settings) { 
     settings.url = SET_DOMAIN + settings.url; 
     } 
 });
Denis Matafonov
  • 2,684
  • 23
  • 30