Post Data to a Remote Server (Cross-domain) with jQuery in PhoneGap
June 19, 2011
Android and iPhone apps built with PhoneGap are (because of PhoneGap's nature) compiled code, and because this compiled code is not a browser, you can execute cross-domain requests. The example code I provide below will not work in a browser, but it does work in a phone emulator (whether Android or iPhone) and, of course, on mobile devices. Concerning where you can place data, this opens a whole world of possibilities, including what you can do with user generated content.
PLEASE NOTE:This example will work on a mobile device and in a mobile device emulator. It will not work in an internet browser.
The HTML Form
This example starts with a basic form in HTML, as seen below.
Once you have the form, we'll need some jQuery to process the form and post the data to a script on a remote server. Make sure you change the postTo variable in the example code below so that it points to your own PHP script.
I am using jQuery.post() to send the data to the server. You can learn more about jQuery.post() on the jQuery website.
Essentially this bit of jQuery takes the data from a form with the id attribute of "infoForm" and POSTs it to a PHP script as a JSON string. Make sure you build the data string you'll submit using jQuery.post() with the names of your form inputs. In other words, make sure you add the data from your form to the JSON data string you're building as part of the jQuery POST request.