Converting a dynamic web site to a PhoneGap application
Earlier today a reader asked me about the possibility of converting his mobile-friendly site into a "real" application via PhoneGap. I told him that this could be very easy. You can take your HTML, upload it to the PhoneGap Builder service, and see what you get. This works with simple HTML sites, but is not going to work well with dynamic sites built with server-side languages. In this blog post, I'll explain why it won't work, and also walk you through an example of converting a (simple) dynamic web site into a PhoneGap application.
Before I begin - two quick notes. I'll be using jQuery Mobile for the UI and ColdFusion for the back-end. This is completely inconsequential to the task at hand. Ok, ready?
First, let's discuss why a dynamic web site can't be simply converted as is into a PhoneGap application. Most of my readers are web developers so you should know this, but when it comes to dynamic server-side languages like ColdFusion, PHP, Ruby, etc, the HTML your browser gets is created dynamically.
Take for example this simple ColdFusion site. When you request this URL with your browser, my web server hands off the request to ColdFusion. ColdFusion does its magic (hits the database) and outputs raw HTML. That HTML is returned to the browser and rendered as is. The same would apply for PHP, Ruby, etc. When you click on the detail page, we hit one template that is passed a URL parameter that instructs the code to load a particular record and display it.
Now - consider PhoneGap. PhoneGap takes your HTML files and packages them up into a native application for your mobile platform. But it is not a web server. You can't bundle in ColdFusion or PHP and have it execute server-side code like in the example above.
Does this mean you're completely out of luck? Not at all. Let's look at how we can convert our code into a PhoneGap application.
First, let's look at the initial application. As I said above, the choice of the server-side language isn't relevant to the discussion. Therefore, I won't go into detail about what the ColdFusion code is doing. Those of you who don't know ColdFusion should be able to mentally map it to the language of your choice. First - the index page.
Then the detail page:
And finally - here is the component that drives the data. Basically it just wraps up the logic to get our list and detail.
Ok - so that's our old school (although nicely mobile optimized) web site. To begin the conversion to PhoneGap, I create a new file for my home page that is pure HTML, no ColdFusion.
Notice that the layout is the same as before, but our content is gone. Previously that was sourced on the server by a database call. So how do we add this dynamic data back in? With JavaScript.
First - let's add some logic to run when the home page is created. This specific event is based on how jQuery Mobile does things, but again, you could do this without any particular UI framework.
This code block performs a HTTP request to our server. (Note: I'm using localhost in the example above but in a real application it would be your site's domain, something.com.) I've built a new set of server-side code just to handle getting and returning data in JSON format. So there's still a server involved, but now it's simply returning data, nothing more. I loop over the result and render it out into the page.
The detail page is built much like the index page. It's a copy of the earlier version minus any code or actual content.
To handle this, back in my JavaScript I added code to run when the page is loaded.
And that - as they say - is basically it. To summarize:
- The code in the PhoneGap application is just HTML and JavaScript.
- The dynamic data from the earlier application was rewritten to expose itself remotely.
- PhoneGap then simply uses Ajax to fetch that data.
I've attached a zip of all the code used for this blog post below. If any part of this doesn't make sense, let me know, and I hope this was helpful.

I have not yet tried PhoneGap but been wanting to. Your tutorial has peaked my interest.
Can one use PHP files with PhoneGap, or does it have to be HTML files? Like to use some includes for a project in mind.
Thanks again Raymond, great share.
Terry
Well, shoot, that was kind of the major point. :) If I didn't make that clear, I apologize. So no - you cannot. It has to be HTML.
To be anal, you can use .txt, .xml, .csv, if you want to use JavaScript to parse them. The point is - you can't use a platform like PHP/CF within the PhoneGap app itself. Rather, you would use it via a network call.
Clearer?
I'm giving a small PhoneGap presentation at work this Friday and I already have several of your pages bookmark to share with the group. Well, now I have to add this one too :)
As a general practice I have moved away from using cf in my presentation pages even on desktop applications and use cf only as a data server. - Conversion to mobile becomes much simpler and imo javascript with jQuery is much better at presentation.
I will refrain from such in the future.
http://www.raymondcamden.com/index.cfm/2012/4/14/D...
That being said - I freaking love Handlebars - and yes - it works on mobile. :)
I think you can use 'server-side' code in a PhoneGap application for both Android and Apple. This example will point to code on a web server
Here is an example for Android.
package com.test.test8t;
import com.phonegap.*;
import android.os.Bundle;
public class test8T_srvActivity extends DroidGap {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setBooleanProperty("loadInWebView", true);
super.setIntegerProperty("loadUrlTimeoutValue", 80000);
super.loadUrl(
"https://www.test_server/apps/folder1/www/index.htm...;);
}
}
(Pretty sure I spelled that accelerator part wrong!)
Also, tomorrow, Andrew Trice and I are doing an open preso you can attend.
Thank you sir!
1) Login is certainly possible. Its just one more Ajax call. If your back end supports cookie-based sessions, then your PG app's Ajax calls will pass those cookies back in future calls. That means your back end code could ensure a session exists (and has a verified login) before returning any data.
2) User based views: Your login method could return a hashmap of allowed views, or roles, that your client app would use to render stuff. Obviously your back end code still needs to do validation, based on the session info.
We are in the process of creating a PhoneGap application and the functionality would also be accessible from the mobile browser.
We are having a discussion as to which option to use:
1) Send json from server and keep html pages in the phonegap app.
2) Send hrml pages populated with data to the phonegap app.
The advantages we see are:
1) Fixing bugs is easier, it is server side instead of getting the app certified all over again
2) Probably more re use of code.
Do you have any comments on this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RYP</title>
<link rel="stylesheet" href="css/jquery.mobile-1.1.0.min.css" />
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.0.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div data-role="page" id="indexPage">
<div data-role="header">
<h1>Shows</h1>
<img src="css/images/ryprad_logo.jpg"></h1>
</div>
<br><br><br>
<div data-role="content">
<a href="intList.html">Shows</a><br><br>
</div>
<br><br><br>
<div data-role="footer">
<h4>Stat</h4>
</div>
</div>
</body>
</html>
Could you suggest a method to fire the event to call and return the data in the emulator?
I created a web site in PHP and I load it in a phone gap app using onload function and ajax. Now I want to call phonegap function from my code in server. For example I want to take a photo can I call that photo function in my app ?
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Art Lister</title>
<link rel="stylesheet" href="css/jquery.mobile-1.1.0.min.css" />
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.mobile-1.1.0.min.js"></script>
<script src="cordova-2.0.0.0.js"></script>
<script src="js/main.js"></script>
</head>
To run you through my process, I did the following:
1. In Dreamweaver, I created a new site
2. I copied the files from your v2 folder into the new site
3. I copied the artservice.cfc to my testing server and made sure it was accessible
4. I change the cfc call in the index,html page to pint to the cfc on my testing server
5. I built the app using the PhoneGap functionality built into Dreamweaver
6. I launched the app from Dreamweaver in an Android Virtual Device that I previously created
The app installs fine in the AVD and opens, just no data is displayed. Only the header and footer show.
Any ideas why the data is not displayed? Thanks!
I'm new to coldfusion and I want to work on PhoneGap. I loaded all your files in a local host and tried to run V1/index.cfm but is shows an error "Datasource cfartgallery could not be found." May i know the reason please?
how to overcome this error
function foo() { alert('x'); }
This cannot be added to the app when loaded in via Ajax. Instead, your code must be written as
foo = function() { alert('x'); }
I tried this example these days, I installed the android sdk, everything ok, but my cfc works if I call the method with returntype="string", but doesn't work with returntype="query". Unfortunately I have no errors from the debug. I call the cfc in the external server with cf8....help help help please....thank you very much
my cfc:
<cffunction name="getfatture" access="remote" returntype="query" output="false">
<cfquery datasource="#request.datasource#" name="sel_fatture">
SELECT CT_Fatture.id_fattura, CT_Clienti.Societa
FROM CT_Fatture
INNER JOIN CT_Clienti ON CT_Fatture.id_cliente = CT_Clienti.id_cliente
</cfquery>
<cfreturn sel_fatture>
</cffunction>
and script:
<script>
$("#indexPage").live("pageinit", function() {
console.log("Getting remote list");
$.mobile.showPageLoadingMsg();
$.get("http://invoice.contechnet.it/object/pg/listFatt.cf...;, {}, function(res) {
$(document).ready(function(){
alert(res.length);
});
$.mobile.hidePageLoadingMsg();
var s = "";
for(var i=0; i<res.length; i++) {
s+= "<li><a href='detail.html?id=" + res[i].id_fattura + "'>" + res[i].societa + "</a></li>";
}
$("#artList").html(s);
$("#artList").listview("refresh");
},"json");
});
</script>
thank you
if i use
alert(JSON.stringify(res, null, 4));
i get
{"COLUMNS":["ID_FATTURA","SOCIETA"],"DATA":[[2,"Receptour Srl"],[3,"Contech Sas"],[4,"Receptour Srl"],[5,"Receptour Srl"],[6,"Zama World Visa"]]}
thank you very very much
regards,
John
I was thinking more along the lines of retrieving the actual HTML in stead of json content and inserting that dynamically. There are some issues to overcome at first glance:
* you would have to create some generic way of handling form submissions that integrates nicely with your existing server side infrastructure.
* returned templates shouldn't contain any script src references.
* you need to deal with session timeouts gracefully
* you would have to do all this and at the same time avoid the Apple AppStore police saying it's too "webby"
Non of this seems major. Any thoughts on this?
var bloc_adresse ='<li><a href="page.html?id='+id+' "rel="external"> '+titre+'</a></li>'; doesn't work. Can you please tell me if you have any idea.
One question is this .cfm will work in iphone too ??
actually i have tried & the problem i got is, below code is written in index.html
<body>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta HTTP-EQUIV="REFRESH" content="5; url=index.cfm">
</body>
when i run my app i m getting an error like :
Failed to load webpage with error: Frame load interrupted..
Can you please help me ??