I am developing an app using phonegap for Android. I want this mobile application to send some data (mostly text) to an external server backed by cakephp, using jquery and json objects.
I am relatively new to cakephp and the MVC structure, and would appreciate some general advice on how to proceed with this in cake. I basically want phonegap to send formdata to the cakeapplication, and have cake save this data to the database. This is the code I am thinking about using for sending data in phonegap:
HTML form:
<form method="post" id="infoForm">
<input type="text" name="first_name" id="first_name" value="" placeholder="First Name" />
<input type="text" name="last_name" id="last_name" value="" placeholder="Last Name" />
<input type="text" name="email" id="email" value="" placeholder="Email" />
<button type="submit">Submit</button>
</form>
Jquery:
$('#infoForm').submit(function() {
var postTo = '//url to cakeapplication';
$.post(postTo,({first_name: $('[name=first_name]').val(), last_name: $('[name=last_name]').val(), email: $('[name=email]').val()}),
function(data) {
alert(data);
if(data != "") {
// do something
} else {
// couldn't connect
}
},'json');
return false;
});
Can anyone provde som general instructions on how process this data in cake?
Thanks!
PHP5 has the
json_encode()andjson_decode()functions which are of great use. If you’re stuck on PHP4 I believe there’s a JSON Compenent for Cake. I can’t say much about the latter, but calling the PHP5json_decode()will result in a PHP object which you can use to construct a Cake data array to be saved in the database.What you want is to have your AJAX function call a method (
add()for example) in the Cake controller which handles saving data to your database. Cake’ssavemethod expects a specially formatted array, the structure of it is detailed here, so you’ll have to manually construct this yourself.Say your modelised database table for PhoneGap data is called “Phonegap” (in that case you would have a
PhonegapModelandPhonegapsController). The data array for saving would have the following structure:The JSON object is probably available via
$this->params['form'](as per here) in the controller, as you’re performing an AJAX post. I’m not entirely sure how much you already know about CakePHP, so if some things need clarification, just let me know.