1

I'm adding a custom header to the AJAX requests so the server knows which version of my wrapper app is making the request. To add the custom header I have

$.ajaxSetup({
  beforeSend: function (xhr) {
    xhr.setRequestHeader('X-MyCustomHeader', 'Value');
  }
});

I need to change to a page on the server that takes some post data, which I do with

$.mobile.changePage("/Controller/PostAction", {
  type: "post",
  data: postData
});

However, I end up with a loading error and a blank screen. Tracing the network requests sent through the app shows that the request to the server ended up as a GET rather than a POST

Without the custom header the changePage call works exactly as it should.

Does anyone know why adding the custom header is breaking it?

Mark Cheeseborough
  • 134
  • 1
  • 2
  • 8
  • What do you mean, "ended up as a `GET`? If you set the type in jQuery, that is the type that will be used, it can't be altered in the pipeline. Perhaps you have some other code affecting this. – Brad M Jun 28 '13 at 14:39
  • With the custom header it does a `GET` to the URL instead of the `POST` I asked for. The only other code involved in the request is jQuery and jQuery-mobile. – Mark Cheeseborough Jun 28 '13 at 14:47
  • Try putting the beforeSend callback inside your changePage ajax request instead of `$.ajaxSetup()`. Adding a request header will never just change a `POST` to a `GET`, there has to be other logic involved. – Brad M Jun 28 '13 at 15:04

1 Answers1

0

It turns out there was some other logic involved in this. Namely, the code in the wrapper app that makes sure the custom header is present for the non-AJAX requests.

As the wrapper app is running on iOS, it's using a UIWebView and has an implementation of webView: shouldStartLoadWithRequest: navigationType:

If the current request did not have the custom header, my implementation was creating a copy of the request and adding the header to it. It then called loadRequest: on the web view with it and cancelled the current request.

I think the cancelling of the request was interfering with the jQuery Mobile changePage sequence resulting in it doing a GET instead of a POST.

My solution was to check if the current request in webView: shouldStartLoadWithRequest: navigationType: is an NSMutableURLRequest and if so just add the header to it and carry on loading (this seemed to be the case when checking in the debugger). The current request is only replaced if it isn't mutable.

I'm not sure if this is now relying on something that could change in future versions of iOS.

That didn't work, so I'm now using a custom User Agent, like this: https://stackoverflow.com/a/1368399/13570

Community
  • 1
  • 1
Mark Cheeseborough
  • 134
  • 1
  • 2
  • 8