Tag Archives: html

Posting HTML Form to External Link in Safari (Cordova/Phonegap)

cordova
While developing a fairly data centric Hybrid Application using Cordova, I had a need to exclude AJAX from my form post and send my post request as a standard HTML form post. My main reason for choosing this way over ajax was that I was posting files as well as a long base-64 uri to a C# script on my server. I had a simple aspx form on the servers receiving end that needed to capture the post values coming from the client-side app. I chose this route because users of our applications are in rural areas where their signal strength on their devices we’re so strong. Sending images and base-64 data can be a large pay-load not to mention the other 206 fields coming from the app.

In the end, I wanted to mimic a ajax post while using Formdata which kept me from having to manually create the data object. I wanted the form to post to a new window but in Cordova, the UIWebView takes over and replaces Safari web browser with their view. Below is a code snippet found at StackOverflow that did it for me… I modified my version a bit more to define my parameters but for the most-part this same code snippet got my form to post to an external link on our server.

My form was simple (be sure to use ‘_system’ in your target not _blank!):

<form method="post" action="http://myurl.com/postThis" target="_system"></form>

In CDVWebViewDelegate.m search for “shouldstartloadwith” and replace the contents of the BOOL with:

     (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:
     (NSURLRequest*)request navigationType (UIWebViewNavigationType)navigationType{

     if([[NSString stringWithFormat:@"%@",request.URL] 
         rangeOfString:@"file"].location== NSNotFound) { 
            [[UIApplication sharedApplication] openURL:[request URL]]; return NO;
      }
      BOOL shouldLoad = YES;

Clean and build your application in both CLI then in XCode and test. I ran through a lot of examples of how to post from Cordova to an external form but nothing actually worked. Seem’s this way the best fix for my time and effort. The result was simple enough.

Ciao!

 

 

Advertisements
Tagged , , , , ,
%d bloggers like this: