Search code examples
jqueryjquery-mobilecordova

Cross-Domain ajax to REST server with jQuery


I'm creating a mobile app using PhoneGap. So effectively I'm writing the app in jQuery Mobile, HTML and CSS.

Here's the problem: The server is a REST implementation. This means that to create a new 'entity' (e.g. user, car, hot babe), the server listens for POST requests. If the server will respond to GET requests by returning existing 'entities'.

How does one get the mobile app to send a POST request from jQuery? This sounds simple, but keep in mind that jQuery will change a jsonp datatype request to a GET, even if you specify POST. Also, keep in mind that the server and the app is not on the same domain, so this request is send cross domain, so setting the datatype to json will not work.

I have been stuck with this for 4 long hours. I can get it to work in the blink of an eye if I only care about GET requests, but getting a POST on the server has proven to be impossible so far.

Here is a simplification of the server-side code:

 class GatewayService extends Service[Request, Response] {
   def apply(request: Request) = {
     request.method -> Path(request.path) match {
       case GET -> Root / "car" => {
         println("---Get car---")
       }
       case POST -> Root / "car" => {
         println("---New car---")
       }
       case _ => {
         println("---Other method type ---")
      }
    }
}

And here's the jQuery code:

function serverRequest(formId, url) {
    var result = ""
    var formData = readFormData(formId);
    console.log("Submitting form:\n"+JSON.stringify(formData));

    $.ajax({
        type:"POST",
        url: url,
        data: JSON.stringify(formData),
       dataType: "json",
        success: function(response){
            alert(response['message']);
            console.log("Received response: "+JSON.stringify(response));
            result = response;
         },
         error: function(jqXHR, textStatus, errorThrown){
             console.log(
                 "The following error occured: "+ jqXHR,
                 textStatus, errorThrown
             );
         },
         complete: function(){
             //Nothing here for now
         }
    });
    return result;
}

If you have any ideas on getting a POST request cross domain with jQuery, please share your secret.

It appears that you cannot simply access a REST server directly from a mobile app developed on jQuery Mobile. Is this correct?


Solution

  • Did you try using CORS instead of using JSONP? This should be supported by all modern browsers (and thus hopefully by phonegap too). This post relates to it: https://stackoverflow.com/a/8773095/773339

    JSONP is limited to GET only.