2

Im building a mobile app on a PhoneGap. I've created several static HTML pages (stored on the phone locally) and trying to load some data from server using AJAX.

$( document ).bind( "mobileinit", function() {
        $.support.cors = true;
        $.mobile.allowCrossDomainPages = true; 
    });

$(document).ready(function () {
    ajaxDeferred = $.ajax({
        url: 'http://example.com/api/isAuthorized'
        type: method,
        data: parameters,
        timeout: 40000
    });

    ajaxDeferred
        .done(function(data) {  

              alert(data.result);     

         })
        .fail(onFailHandler);
}); 

On a server side I have this code

public ActionResult IsAuthorized()
{
        FormsAuthentication.SetAuthCookie("shade", true);

        return this.Json(
            new
                {
                    result = this.HttpContext.User.Identity.IsAuthenticated
                },
                JsonRequestBehavior.AllowGet
            );
 }

I expect:

  • On the first run recieve "False" result since user is not authorized
  • On the second run recieve "True", because of SetAuthCookie

When I try it in a browser, it works as expected. But whatever I run mobile app i alwayes recieve False, like cookies are not being tranfered.

So the question is how to correctly login user with AJAX, is it possible? What are best practises? For unknown reason this simple scenario is not covered by PhoneGap manuals.

ADOConnection
  • 1,040
  • 12
  • 29

1 Answers1

1

Ok, I found an answer:

$(document).ready(function () {

   ...

});

is not suitable. Instead one have to use

document.addEventListener(
  "deviceready",
  function() {

     ... at this point cookies are working fine!

  },
  false);

Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers are not required as well as other cross-domain techniques

ADOConnection
  • 1,040
  • 12
  • 29