Sam Croft

Full-stack developer

Updated: loading external data into an iOS PhoneGap app using jQuery 1.5


Filed in: iOS, jQuery, JSON, MySQL, PhoneGap, php

Update: Following the release of PhoneGap 1.0 and XCode 4 I have updated the Git repository to include a version built with PhoneGap 0.9x (the original version) and a separate version for PhoneGap 1.xx+.

Update: Due to some issues with the recent versions of Cordova I have updated the Git repository to also include a version built with Cordova 1.7.0.

My 2010 post about loading data into a PhoneGap application is by far the most viewed page of my blog so I thought I’d revisit it and write an article about a more efficient method I have been using, following the release of jQuery 1.5.

Previously I had been using the wonderful JSONp jQuery plugin because jQuery 1.4 and lower did not support out of the box error handlers for JSON requests. jQuery 1.5 does, however, and it’s made things simpler and more streamlined.

Loading data into PhoneGap the easy way with jQuery 1.5

With jQuery 1.5 it’s really simple to load external data into a PhoneGap app. The process is very similar to my previous method, just with a few subtle differences and of course; with the added benefit of not having to include a 3rd party plugin.

Using jQuery.ajax() function to create a basic data request

This is such a powerful little function and, in my experience, is often the backbone of a PhoneGap app that relies on harnessing external data.

	url: '',
	dataType: 'jsonp',
	jsonp: 'jsoncallback',
	timeout: 5000,
	success: function(data, status){
		//data loaded
	error: function(){
		//error loading data

While this is an easy to understand function, there are a few important aspects that bring the whole thing together.

Lines 2 – while PhoneGap uses the file:// protocol and doesn’t have problems with cross-domain requests, I find that using the JSONp data type brings with it two wonderful benefits. Firstly, you can debug your app in a browser—a much simpler approach than using XCode’s console (if you’re working with iOS). And secondly, you have the added benefit of creating code that you can deploy in a browser based version of your app, circumventing any cross-domain issues.

Line 3 – when using the JSONp data type, one must provide a JSONp callback parameter. This is automatically appended to your URL and the value of which must be used within your server side code that outputs the data. This is what allows for the cross-domain request.

An example of how to load external data into a PhoneGap app

In my previous article I was loading a Twitter JSON feed into an app. This was fine at demonstrating the methods of bringing in that data to a PhoneGap app, but glossed over any server side functions that you would be required to create to setup the whole process.

What follows is a method that I have used to create server-side components that will output a JSON object being requested by a PhoneGap app. As an example I will run through the steps to create a fictional app that requests the names of and geo location coordinates of famous UK landmarks.

Creating a simple MySQL database to hold data that the PhoneGap app will request

The first step is create a database that will contain all of the information that the app may request. This article isn’t really about MySQL so I will run through this relatively quickly.

CREATE TABLE 'landmarks' (
	'name' varchar(50) DEFAULT NULL,
	'lat' decimal(18,12) DEFAULT NULL,
	'long' decimal(18,12) DEFAULT NULL,

Within this table I will add the names of some famous UK landmarks and their latitude and longitude values.

Using a bit of PHP to handle a data request from the app and create the JSON object

With a few lines of PHP we can then query the landmarks table in the database and create the necessary JSON output, appending this to the aforementioned JSONp callback parameter.

header('Content-type: application/json');

$server = "localhost";
$username = "root";
$password = "";
$database = "landmarks";

$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);

$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
	$records&#91;&#93; = $row;


echo $_GET&#91;'jsoncallback'&#93; . '(' . json_encode($records) . ');';

What the above snippet of PHP does is query the landmarks table and creates a JSON object with data from the result rows from the query. Note: on line 18 mysql_fetch_assoc is used to create a key=>value array before being converted to a JSON object on line 24.

The query in this example is very basic and is just intended to demonstrate the process. You must add your own MySQL connection details.

For reference; the JSON object returned would be an array in the following format:

        "id": "1",
        "name": "Big Ben",
        "latitude": "51.500600000000",
        "longitude": "-0.124610000000"
        "id": "4",
        "name": "Hadrian's Wall",
        "latitude": "55.024453000000",
        "longitude": "2.142310000000"
        "id": "2",
        "name": "Stonehenge",
        "latitude": "51.178850000000",
        "longitude": "-1.826446000000"
        "id": "3",
        "name": "White Cliffs of Dover",
        "latitude": "51.132020000000",
        "longitude": "1.334070000000"

Using jQuery to load the JSON object

Now that we have our PHP component creating a JSON object we can use some jQuery within our PhoneGap app to load the data.

	var output = $('#output');
		url: 'landmarks.php',
		dataType: 'jsonp',
		jsonp: 'jsoncallback',
		timeout: 5000,
		success: function(data, status){
			$.each(data, function(i,item){ 
				var landmark = '<h1>''</h1>'
				+ '<p>'+item.latitude+'<br>'
				+ item.longitude+'</p>';
		error: function(){
			output.text('There was an error loading the data.');

The important part in this snippet is lines 10 – 16. What happens here is that a function will iterate through each item in the JSON object array and retrieve the values using their key name. The results of which are then appended to an HTML element.

If you encounter an error when loading your data resource, check my article on how to handle ajax errors, when you’re loading external data, with native PhoneGap notifications.

Running this application, you should see something like this:

Famous UK landmarks and their geo location listed in an iOS PhoneGap app
Famous UK landmarks and their geo location listed in an iOS PhoneGap app

Using PhoneGap 1.x+?

With PhoneGap 1.0 a new section was added to the project plist file, ExternalHosts. With this change you must whitelist servers that you access from within your app, so make sure to add any domains. In my example app I simply add as a new item within ExternalHosts.

Highlighting the PhoneGap 1.0 server whitelist ExternalHost section
Make sure you add your domain to the ExternalHosts section of the phonegap.plist

PhoneGap will not be able to load resources from external sources unless you complete this step.

About the author

I'm Sam Croft a full-stack developer with over 15 years experience in web and app development. For the last six years I have been a partner of Running in the Halls, an app and game design studio based in Huddersfield, UK. During this time I have developed many web and applications. Highlights include a node.js/ app to create the worlds largest crowd-based game on the first series of Channel 4's Gadget Man with Stephen Fry and Librarygame, a Library gamification platform for Universities. Librarygame is being played by over 6,000 students at The Open University, The University of Manchester, The University of Glasgow and The University of Huddersfield.

In my spare time I enjoy long distance running, watching all sports (especially F1) and playing video games. I live in the Holme Valley in West Yorkshire with my wife, Alex.

Sometimes I tweet.

  • Pingback: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access()

  • Thank you Sam, this is really great and inspiring, you have very nice post on phone gap

  • Matt

    Hi Sam!

    This is a great tut thanks so far!

    Because I don’t want to use vars in my links to get data from my PHP file like file.php?var=foo do you have an idea how to fix this ?

    I think we need some jquery POST/response ?

    Some example would help I think!

    Have a nice beer ;)


  • Jérôme

    Dear Sam,

    many thanks for your tutorial, short, relevant.

    I am facing the same problematic as Matt ( to get data from my PHP file like file.php?var=foo …)

    Do you think you have the time to answer to this post.

    Many thanks in advance,

  • Sam Croft

    Hi Matt/Jérôme,

    I haven’t tested this, but I imagine you’d require something like this:

    type: ‘POST’,
    url: ‘landmarks.php’,
    data: {name: “Big Ben”},
    success: function(data) {
    $.each(data, function(i,item){
    var landmark = ‘


    + ‘


    + item.longitude+’



    Very similar, but using instead

    I’m not sure how this will work with cross-domain requests (outside of PhoneGap).

    I hope this helps, and best of luck :)

  • David

    Excellent, thank you Sam.

    Just a question : If I would like to use this tutorial, but replacing the PHP / MySQL server side by a Google App Engine(Java EE) / Bigtable app, is it the same simplicity or there are special things to consider?

  • Anonymous

    Hi David,

    I haven’t ever used Google App Engine before, but as long as you can output a JSON/XML response it should be no different. The server component can by anything, I just usually use PHP/MySQL :)

    Best of luck, let me know how you get on.

  • David

    I’ll try it soon :)
    Howewer, I’ve been advised to use Jersey or Restlet to make communicate both sides. What do you think about them ? Why you don’t use this kind of “framework” ?

    Also, there is no json_encode in Java, I’ll have to use a lib like GSON or Jackson.

    Erf, life seems easier with Php, don’t move ^^

  • Anonymous

    I have very little experience with Java, I’m afraid. I remember a bit from a module at University, but that was 10 years ago!

    Yes, certainly sounds easier with PHP ;)

  • Russell Barber

    Hi, Great post and info. Just what I was looking for. I do have a follow up question. If I have the location of an image stored in my server side db, and that location is in a folder on my server… How can I bring back the image and render it in my app?

    Thanks again.


  • Anonymous

    Hi Russell,

    This is relatively straightforward. 

    Firstly ensure that the field that contains the path of the image is included in your SELECT statement.

    Then when you are dealing with the JSON you just need to append an . Using my example it would be something along the lines of:

    $.each(data, function(i,item){
    var landmark = ‘<h1>’'</h1>’
    + ‘<p>’+item.latitude+'<br>’
    + item.longitude+'</p>’ + ”;


    This assumes that you are storing absolute URL’s in your database.

    I hope this helps. Best of luck :)

  • Russell Barber


  • Slaw

    This is exactly what I was looking for….. absolutely brilliant!!!!! Simple to the point and easy to extend!!!!!! THX

  • Anonymous

    You’re welcome, glad you found it useful :)

  • Does this work with phone gap 1.0 because after creating all the files with the code stated, however It does not seem to work for me…? :/

  • Anonymous

    You’re right, there does seem to be an issue with 1.0.

    I would suggest creating a new project and adding the JS manually. 

    Alternatively, have you seen these notes regarding migration to 1.0? 

    “NOTE: If you don’t want to migrate to a new project (migrating is HIGHLY recommended), you need to copy PhoneGap.plist from the new project into your own project, and the phonegap.*.js files, then modify your index.html script tag”

    This is definitely the issue.

  • Quentin Berder

    Thanks a lot for the post, very interesting!

    Only have a question, how will you do to store the data on the device? Will you use localStorage or Lawnchair? And how will it look then? Thanks in advance.

  • Thanks for the response, I got it working in the end. I was just wondering if there was a way of displaying more information about each outputted row when you click them. Say you display a list of items and then when you click on one you are shown some more columns of data according to the name of the row…? Thanks

  • Briansosing

    Hi , i have a big problem , when i upgrade phonegap by 0.9.5 to 1.1.0 , i can’t use jsonp , can you help me ? thx .

  • Badbrandn

    Hi! , i’m trying to do an android app with phonegap and jsonp but always appear :
    11-18 14:31:27.873: D/PhoneGapLog(609): http://mydomain/?jsoncallback=jQuery164044945263490080833_1321626474986&set=1&_=1321626687183: Line 1 : SyntaxError: Parse error11-18 14:31:27.873: E/Web Console(609): SyntaxError: Parse error at http://mydomain/?jsoncallback=jQuery164044945263490080833_1321626474986&154caim1an1u85ds413=ds5fa4&_=1321626687183:1I really need help =_/ !

  • Anonymous

    Does your JS work outside of PhoneGap? Do you get any errors if you test it in a browser?

  • Dennis West

    I am having a callback problem I believe.

    I can execute the url: http://localhost:8888/JQueryMobileSite_70/www/landmarks.php
    and it returns in the browser. the proper sql selection from landmarks.php.  But when I execute it, within PhoneGap 1.2.  I get the Msg.- There was an error loading the data. The data was loaded, I have tested that, but it was not returned? what am i doing wrong??

  • Anonymous

    Hi Brian,

    You need to add your domain to PhoneGap’s new server whitelist section in your app.plist file.

    Look for the ExternalHosts section and add your domain name. That should fix it :)

    I will update the post with this information.

  • Anonymous

    Hi Dennis,
    PhoneGap have added a server whitelist feature that prevents this from working unless you flag your domain.

    Look for the ExternalHosts section in your app.plist file and add your domain name.I will update the post with this information.

  • Jithesh Pk

    Can you please tell me where we can add ExternalHosts entries…
    I am using phonegap  + Eclipse in Ubuntu..
    I cannot locate the mentioned file phonegap.plist


  • Anonymous

    Hello Jithesh,

    Phonegap.plist is for iOS apps only. It sounds like you’re developing for Android? If so I think you need to add your external hosts to the phonegap.xml file, try…

  • Jithesh Pk

    Thanks for the information…
    I have added the domain url to phonegap.xml
    But still getting the message “There was an error loading the data”
    Can you tell me any possible reasons?

  • Anonymous

    Have you added the internet permission to your manifest.xml?

  • Jithesh Pk

    Yes , its there in AndroidManifest.xml file

  • Anonymous

    What error do you get if you test it in a browser? Check the network tab in the developer console for the resource you’re loading and see what http status it is returning.

  • TatMac

    Excellent Tutorial. I was wondering if it is plausible to also send data back to the database using this method of JSON and AJAX via html forms? I’m guessing it would also require separate php page(s) to pass the form variables back with the relevant update/insert/delete commands? Or is there a simpler method of doing this? Any suggestions appreciated.

  • hi sam! great tutorial. Is it possible to parse an external xml-file with this code?

  • Simon B

    Dear Sam, Thanks for this really great tutorial. It works excellent with PhoneGap 1.20. Now I’m looking for a solution, to send the contents of a contact form to a php script on my Server for mailing. How would you implement it?

  • Anonymous

    Thanks :) 

    Yes you would need a PHP script, or any other server side language, to handle your data. You can easily pass data back using jQuery’s $.get() function

    I will write an article about sending data back to the server soon.

  • Anonymous

    Hi Simon,

    See comment above in reply to TatMac. Essentially you will need to use jQuery’s $.get() function to pass your variables to a PHP script with your mail function.

  • Simon B

    Hi Sam,

    Thank you for your quick response :-) I thought, the “get” used for the transfer from the server. And post for the transfer to the server. My form contains three fields. (last_name, first_name, email) My php script expects the following fields. Should it work?<?php$_POST['first_name'];$_POST['last_name'];$_POST['email'];$firstname = $_POST['first_name'];$lastname = $_POST['last_name'];$email = $_POST['email'];$emailSubject = 'New Message';$mailto = '';$body = <<<EODName: $firstname Email: $lastname Question: $eamil EOD;$headers = “From: $emailrn”; // This takes the email and displays it as who this email is from.$headers .= “Content-type: text/htmlrn”; // This tells the server to turn the coding into the text.$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.?>

  • Simon B

    Sorry, here’s my php script

  • Anonymous

    You’re absolutely right. POST would ordinarily be used if you were sending from your domain, but you cannot post cross domain.

    Using GET you can send additional data to your script.

    As per jQuery’s example…

    $.get(“”, { name: “John”, message: “Hello” } );

    Is the same as:

    So, using the data attribute you can send over your variables and then pick them up on your php script…

    $firstname = $_GET[“name”]

    I hope this helps some :)

  • Simon B

    Hi Sam, your solution works great. The email delivery works also fine. Unfortunately I still have a problem. How can I get my form fields dynamically in the GET string? I hope our conversion helps others too.

    My form:
    My Script:                $(document).ready(function() {                                  $(‘#Button2’).click(function() {                $.get(“”, { ??? } );                });               });                   

  • Anonymous

    Hey Simon,

    You can use jQuery’s .serialize() which will go through your form and add all the values to your .get request in the data attribute.

    So you would have something like;

    $(‘#button2’).click(function(){ var sendthis = $(‘form’).serialize(); $.ajax({ url: ‘’, data: sendthis, success: function(){ console.log(‘sent!’); } });});

  • I tried it with the “serialize()” alert example of JQuery page. The string is displayed correctly. Unfortunately, it does not work with your function. I can’t find the error :-(
    $(document).ready(function() {

    $(‘form’).submit(function() {
    return false;});});

    works brilliant but this function don’t work :-(

    $(document).ready(function() {


    var sendthis = $(‘form’).serialize();



    url: ‘http://mydomain/parser.php’,

    data: sendthis,

    success: function(){



  • Anonymous

    Hi Simon,

    Did you get this sorted? Apologies, I didn’t actually test that snippet I sent you.

    In your code above you’re missing some parentheses for your error function.

    Try this. If you open your browser console (inspect element>console) you’ll see the serialized var. It will also say error, until you add in the correct domain>script to send your data to:

    $(‘form’).submit(function(){  var sendthis = $(‘form’).serialize(); console.log(sendthis); $.ajax({ url: ‘http://mydomain/parser.php’, data: sendthis, success: function(){ console.log(‘Sent!’); }, error: function() { console.log(‘Error!’); } }); return false; });

  • Hello Sam
    how I could adapt the example so that the data are presented in gmaps. I’m built an application that takes the user’s location and looking around houses for rent or sale and displays the map. The strategic housing for rent already registered in my database.


  • Simon

    Hi Sam,
    meanwhile everything works fine. Later i’ll post my results. Thank You :-)

  • Hi , I’m new on the app developement using phonegap , so I first tried your example only using my browser and hotlinking your landmarks.php file , it doesnt seems to work , do I need to work only using local files?  I just want to get an external json file from a different domain and display the data.

  • Anonymous

    Hello Moyado,

    If you’re testing in your browser you will need to comment out the deviceready callback function, lines 2 and 23, as it is intended for use within a PhoneGap app.

    That should work.

  • Anonymous


    This is quite complex but essentially when you iterate through the items in your json or xml you add a new maps maker with the latitude/longitude. Something like;

    $.each(data, function(i,item){ var marker = new google.maps.Marker({ position: new google.maps.LatLng(item.latitude, item.longitude), map: map, title: });});

  • Zac

    It looks like v1.5 of jQuery adds a crossDomain boolean argument to the ajax() method, so it may be possible to perform the cross domain request without needing the additional plugin.

  • Nn


    Im trying to open pages in-app in my phonegap iphone app, can i use your function to bring a full page as is into my app or iframe in it ? if yes can u tell me how ? like a sample plz.


  • Anonymous

    Hi Zac,

    What plugin are you referring to? This method only uses jQuery 1.5, nothing else. But yes, this is only possible due to the changes in 1.5.

  • DenBeke

    You could do, but Apple would never accept your app…

  • Hi Sam, 

    Things are working .. thanks for the tips :)
    Can you tell me how we can include a splash waiting screen in our app.

  • Adskiremote

    Sam thanks for a great tutorial…

    Maybe someone will find this useful, I’ve modified the connection to use PDO.

    My example based on your landmark.php:


          #MySQL with PDO_MYSQL  
          #$DBH = new PDO(“mysql:host=$server;dbname=$database”, $username, $password);  
          #$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
        catch(PDOException $e) {  
            echo $e->getMessage();
            echo “There is an error”;
            #Log the error
                    file_put_contents(‘PDOErrors.txt’, $e->getMessage(), FILE_APPEND);

    #Execute the query and fetch the rows
    $records = array();
    $STH = $DBH->query(‘SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks ORDER BY l_name’);


        while($row = $STH->fetch()) {
                    $records[] = $row;
    #Close the connection
    $DBH = null;

    echo $_GET[‘jsoncallback’] . ‘(‘ . json_encode($records) . ‘);’;

  • Anonymous

    I’m not familiar with PDO but thanks for sharing this Adskiremote!

  • Pingback: PhoneGap/iPhone Crib Sheet – Handy Links « iPhone Dev Log()

  • Nolo2000000

    Hi Sam this seems fairly straight forward.
    I was hoping for a “complete” code sample however can’t seem to find one.  I’m not familiar with GitHub, however drilling down through the folders etc. still didn’t provide me with an “Index.html” iPhone file, nor did I see a “remote” file.
    This is EXACTLY the technology I need for an application idea, but I am stumped.

  • Sam Croft


    Look for the zip button on the top left of the GitHub page. It will download the entire project. When downloaded open the relevant phonegap folder and load the project file to open in Xcode. If you’re looking for the HTML and js, drill down into the www folder.

    Everything you need is in the zip :)

  • Netinkickass

    thanks mate!!! you saved my arse!! =D


  • Pingback: Posting data from a PhoneGap app to a server using jQuery()

  • Mark

    I was struggling with this issue, getting info from an external source, thank you!!

  • Sam Croft

    Glad this helped Mark.

  • Anthony

    Wow! Been looking for this for days now. Can’t wait to give it a try. Thank you for taking the time out for this!

  • I’ve been trying to get this to work in a browser (not even phonegap)
    with the AJAX URL directed to your page, it works like a charm
    if I change the URL to my own webserver, and add the json on my server..
    I get nothing but an error: Error: jQuery171010694300881272145_1331125821253 was not called

  • Does it have the correct content header? It should be: Content-Type:application/json

    If you look in the developer console in your browser and check the network tab (Chrome) what does it say for the json resource? This should give you some useful debug information.

  • Craig

    Sam – excellent information and extremely helpful.  Newbie to AJAX and have a simple question regarding securing the data.  If I use the ‘GET’ to pull from a https url, with the url string as ‘http://user:pass@domain:disqus 
    .com’ how secure is the transfer of the data?  I’ve got the thing working no problem, just worried about security.  I have very little knowledge regarding HTTP security across the wires.  Thanks, hell of tutorial and PhoneGap is quite the useful tool.


  • Glad you found this useful, Craig.

    Providing your ajax calls are via https then your data is secure. I have used https in a few apps and don’t recall any issues.

    I hope this answers your query :)

  • Yes, there was the content header json

    but the problem relies in my cors settings (
    this was no where written how to set these.. took me some effort to find all correct info..
    but I managed :) thanks for the awsome follow up.

  • Thanks for mentioning this here. It should work without CORS though… JSONP is an alternative to CORS.

  • Craig

    It does, thanks, this stuff is really cool.  Any good books/online guides you recommend for soaking up more of this AJAX / JQuery stuff?

  • The jQuery documents are great and always provide examples for every method/function. And the PhoneGap Google Group is a great place for seeking help with specific problems

    For PhoneGap in general I recommend giving Jonathan Stark’s Building iPhone Apps with PhoneGap a read – it’s what got me started in 2009.

  • Craig

    Thanks man, I was checking out his book on Amazon, I will pick up.  Quick question and I will not bother you again (today).  Why would the following not render correctly:

    var landmark = ‘‘’ ‘ + ‘‘+item.question+’

  • You have a few too many quotes before you concatenate the html input element. Try:

    Or, if you’re adding +' '+ to form space in between each variable:

    What are you trying to produce? It’s hard to see just from the snippet you posted.

  • Pingback: I T | Pearltrees()

  • Xfreakart

    Hi, nice tutorial.

    I’m new in phonegap, I’ve modified the url in the js for a local one, and the json works fine.
    My problem is when I try to run the source code. I have a: “PhoneGap/PhoneGapDelegate.h file not found” error.  Has someone solved this ? I use Xcode 4 and phonegap-1.2.0.js (the one that comes with zip source). I haven’t change anything else in the source code.



  • Anonymous

    Not sure what happened. Since the switch to Cordova, this doesn’t seem to work. I’ve added all my servers including * to the ExternalHosts file and I still get a Whitelist rejection.

  • Renee

    Hi! I’m brand new to PhoneGap and to JSON, and your tutorial is the most helpful I’ve found online so far. Since you come up at the top of the Google search for ‘phonegap mysql’, I would suggest adding a little more info for beginners.

    For instance, where does the PHP file get saved – in the project or on the server with the database? I would guess it gets saved in the project since you’re referring to it as url: ‘landmarks.php’, but I really don’t know how all of the pieces presented here fit together.

    I’m off to go figure it out, but any help would be appreciated! Thanks for the great info!

  • Renee

    Now I see the PHP page is referring to the server as “localhost”…

  • Hi Renee,

    You are right – this article does assume quite a bit of knowledge about how this kind of architecture works.

    The PHP file must be on your web server, it is completely remote to your app project. In my example I am running a server that contains both the database and the PHP file. From within the app I use the address of the server to call the PHP. If you’re testing this locally on your computer, the server would (ordinarily) be localhost (instead of 

    I hope this explains things a bit clearer. Let me know if I can help in any other way.

    – Sam

  • That’s interesting. I haven’t tried it with the latest release. I’ll give it a try when I have a few minutes and see what I find…

  • I’ve just tried it with Cordova 1.7.0 and it seems to work fine. I created a new project and just added the js manually.

    There was no issue with the ExternalHosts in Cordova.plist.
    There did seem to be a conflict with the ondevice ready function, however, – so I changed that as per Nic Haynes setup with jQuery –

  • Nick D

    Thank you Sam for this. You have cleared up a lot of questions.
    One last sticking point for me. I have done everything you suggest, testing in a web browser everything works perfectly. However when I compile the app to test on an iPad I get a completely blank screen. I am using phonegap1.4.0 and have allowed external domains.
    I know this is a very “wooly” question and it could be many things but I was wondering if you could suggest anything that I should look out for.



  • Hi Nick,

    Have you linked the www folder to your application? You need to drag the www folder into your xcode project browser and add it as a reference. Apologies if you have already done this, but that is usually the issue if you are just seeing a white screen.

    Check the xcode console log as well, does it give you an type of error message there?

    – Sam

  • Smiley1ds

    Thanks Sam for the awesome a article but I have one question wouldn’t this method create a security risk 
    anybody who get hold of your url “” could access the data in your database without having app or any database passwords

  • There is always a risk when you expose data like this. How that is handled is always dependant on the data you’re making available and to whom. This article covers things in their simplest form. 

    In a live situation extra steps could be taken server side to ensure access of the database resource was only available through the app, via a particular referrer or through a certain type of http request. It always comes down to what kind of data your accessing and how public/private you intend it to be.

  • Smiley1ds

    Ok thanks

  • Thanks, you’ve been bookmarked alongside StackOverflow ;-)

  • Renux

    First of all thank you for the post, and sorry for my english =_=
    I ‘m  doing a app for iphone and I use your method
    Is posible put the a list in the php?

    This is the code but not work:

    $(document).ready(function(){ /*$(document).bind(‘deviceready’, function(){*/ var output = $(‘#output’); $.ajax({ url: ‘’, dataType: ‘jsonp’, jsonp: ‘jsoncallback’, timeout: 5000, success: function(data, status){ $.each(data, function(i,item){  var cinemessantboi =  ” ” ”’‘/**/+item.titulo+”” ”’”Lunes a Viernes:””’   ”+item.horarios1+” ”’”Sabado y Domingo:””’ ”+item.horarios2+’‘ ” ” output.append(cinemessantboi); }); }, error: function(){   output.text(‘There was an error loading the data.’); } }); /*});*/});


  • Renux

    Hi Sam!

    I have a problem with browser

    This code not work, any idea?

    $(document).ready(function(){ /*$(document).bind(‘deviceready’, function(){*/ var output = $(‘#output’); $.ajax({ url: ‘’, dataType: ‘jsonp’, jsonp: ‘jsoncallback’, timeout: 5000, success: function(data, status){ $.each(data, function(i,item){  var cinemessantboi =  ” ” ”’‘/**/+item.titulo+”” ”’”Lunes a Viernes:””’   ”+item.horarios1+” ”’”Sabado y Domingo:””’ ”+item.horarios2+’‘ ” ” output.append(cinemessantboi); }); }, error: function(){   output.text(‘There was an error loading the data.’); } }); /*});*/});

  • Hi Renux,

    A few of your strings weren’t properly formed. Try this in place of your current $.each method:

    $.each(data, function(i, item) {
    var cinemessantboi = item.titulo + ‘Lunes a Viernes:’ + item.horarios1 + ‘Sabado y Domingo:’ + item.horarios2; output.append(cinemessantboi);});

  • Avinash

    hello sir I am beginner to phonegap how to make HTML page get data from server useing ajax request and json data formate……….

            PhoneGap Ajax Sample
            document.addEventListener(“deviceready”, onDeviceReady, false);   
            function onDeviceReady() {

                        url: ‘’,

                            dataType: ‘json’,

                            jsonp: ‘callback’,
                           error: function(XMLHttpRequest, textStatus, errorThrown) {
                            success: function(data) {
                .tweet {padding-bottom:5px;}
                .avatar {float: left; height: 48px; width: 48px;}
                .tweet_content {margin-left: 60px; min-height: 48px;}

     i am using this coding i  am not getting data to html page pls help

    thanks and regards
    Avinasha NV

  • cnusinov

    Sam – 

    Can you expand on your change made per Nic Haynes?  I am having the same problem. Just upgraded a bunch of scripts to Cordova-1.7.0. and the script now fails.  I am getting a message from Xcode: 

    2012-06-13 07:56:50.471 JSON[36471:707] [INFO] Error in success callback: NetworkStatus0 = TypeError: ‘undefined’ is not an objectI’ve only worked with this for about 4 months or so (JSON, AJAX, etc.) so this is a new one for me.  Do you have a remedy or can you explain when you have a moment.  Thank you!Craig

  • Hi Craig,

    This seems to be an issue with initialising jQuery and Cordova’s ondeviceready function, in that one is happening before the other and failing.

    Nic’s solution is to approach this as follows:

    $(document).ready(function() {
    $(document).bind(‘deviceready’, function(){
    // Phonegap ready
    // Your main code

    Give that a try. I think it will resolve your issue. Let me know :)

  • Craig

    Thanks for reply – maybe 5 hours of sleep x 3 nights is not helping, I keep getting same xcode error, here is my index.html, 

          $(document).ready(function() { 
                            $(document).bind(‘deviceready’, function(){
                                             // Phonegap ready
                            // Your main code

  • Craig

    Sorry man, like I said, no sleep, here is index.html:

             $(document).ready(function() { 
                               $(document).bind(‘deviceready’, function(){
                                                // Phonegap ready
                               // Your main code

  • Where you have “//your main code” is where the contents of load-json.js should be. Like so:

    $(document).ready(function() { 
                               $(document).bind(‘deviceready’, function(){
                                                // Phonegap ready

    var output = $(‘#output’); $.ajax({ url: ‘’, dataType: ‘jsonp’, jsonp: ‘jsoncallback’, timeout: 5000, success: function(data, status){ $.each(data, function(i,item){ var landmark = ”” + ”+item.latitude+” + item.longitude+”; output.append(landmark); }); }, error: function(){ output.text(‘There was an error loading the data.’); } });


  • Dan

    Hi Sam,

    Thanks for the great tutorial, I am actually using this as part of an app that is available on the app store. I was wondering if you had any tips / expertise about using this alongside with urban airship. So that whenever a new item in the database is added, it can send a push update? I’d be very interested if you had any input.



  • Hi Dan,

    I haven’t had any experience with Urban Airship, but from what I’ve read it is quite well documented and reasonably straightforward to integrate with. Would love to hear how you get on with it though.

    – Sam

  • Craig

    Thanks Sam – I will give it a go when I upgrade back to Cordova 1.7 / 1.8.  I’ve been disconnected for the week, and I appreciate the help!  Have a nice weekend across the pond!

  • ranjith kumar

    Hi sam, 
    I am trying to work with an php generated XML file(the XML content is with in the .php file as your json generated i generated XML), could you please help me out: 
    1.Do i need to follow any specific rules in generating XML file?
    2.Could you please provide XML API as I could n’t able to find it??

  • Thanks Craig. Let me know how it works out :)

  • Hi Ranjith,

    I’ve never tried this with XML, but I imagine the technique is very similar. Check out this guide regarding jQuery and reading XML

    Essentially you need to change the dataType from jsonp to xml and then iterate through each xml field using jQuery’s find() method. For the fields you are iterating through you then need to use the find() method to pick out the necessary values. I think…

    Hope that helps.

  • Pingback: Need help with getting started. - Android Forums()

  • Greg

     Same problem.  Google search is not returning any useful tips on this.  Anyone got any ideas?  I am completely new to this so I could be missing something very obvious.

  • Are you using a version of PhoneGap or the new Cordova versions? If you’re using the latest Cordova builds then you will need to link to the cordova.js file instead of the old phonegap-1.2.0.js file. 

    I will update things on Github to reflect this.

  • See above. Make sure you are using the correct js file that matches the version of PhoneGap/Cordova that you have installed.

    Let me know if that solves the issue.

  • Greg

    I am using the very latest version of Cordova but the project I am trying to work on was written in an older version (Phonegap) so that does indeed sound like you’ve got my issue figured out.

    I got the latest Cordova version here at so I guess I have version 1.8.1

    Sorry to ask the really stupid/obvious question here, but what is the name of the correct file to include?

  • Hey Greg,

    Ah I see. I believe I encountered this issue some time ago as well. Sadly, the work around was to create a new application and migrate the code. It’s a sucky solution but is probably your best bet.

    I’d try creating a new app with nothing in it and just make sure you can build that without any errors before migrating though. Just to make sure Cordova has installed correctly.

    Let me know how you get on :)

  • Pingback: Handling errors with native notifications in a PhoneGap/Cordova app()

  • Pingback: Security issues with phonegap remote server access()

  • Stefan

     Hi Sam,

    thanks for the great tutorial.
    I’ve built a news archive with teaser messages at first. This works so far.

    Here is the sql statement: $sql = “SELECT id, headline, date, teaser, text FROM news WHERE published = ‘1’ ORDER BY date desc LIMIT 0,10″;

    Furthermore the ajax method:
            url: ‘nachrichten.php’,
            dataType: ‘jsonp’,
            jsonp: ‘jsoncallback’,
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){
                    var nachricht = ”+item.headline+”
                    + ‘‘’
                    + item.teaser+”;
            error: function(){
               output.text(‘There was an error loading the data.’);

    Now the problem, how do i reach the full data(item.text) at another external site? Do you know what i mean and have you any ideas how can i implement it?

  • Hi Stefan,

    I’m not sure I understand what you mean by item.text at another external site? Can you explain it further?

    – Sam

  • Stefan

    Hi Sam! item.text is another data field from my data table. The result should be to display all messages from the news table in series. And when you will click on a link “read on” you will see the full message(item.text) on a “new” page. Do you have any idea? Thanks for your help :) Stefan

  • Ah, I understand what you mean.

    Are you using any kind of mobile framework? jQTouch perhaps? I have done this kind of thing many times using jQTouch.

    Essentially you would have item.headline as a link, and have the article id as an attribute in the link, data-news-id=”‘'” for example. 

    You can then obtain this id when the link is tapped and use it as a parameter in a separate data request, just for that article. Something like nachrichten.php?id=xx

    I hope that makes sense?

  • Stefan

     Yepp, that is what i mean.

    I’m using jquery mobile, but it doesn’t work :(

    that’s my index.html

        jQuery Mobile-Webanwendung

            Seite eins


    load-json.js is similar to your file, with a little extension on line 18: read on …
    On the next page named nachricht.html, i defined also a div named “output2″ and a second js-file.

        $(document).bind(‘deviceready’, function(){
            //Phonegap ready
        $.urlParam = function(name){
            var results = new RegExp(‘[\?&]’ + name + ‘=([^&#]*)’).exec(window.location.href);
            return results[1] || 0;
        var nachrichtid = $.urlParam(‘id’);
        var output = $(‘#output’);

            url: ‘app/nachrichten.php’,
            dataType: ‘jsonp’,
            jsonp: ‘jsoncallback’,
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){
                    if( == nachrichtid) {
                        var nachricht = ”+item.headline+”
                        + ‘‘’
                        + item.text+”;
            error: function(){
               output.text(‘There was an error loading the data.’);

    But as i told you, it doesn’t work :(

  • Stefan

    hi sam. i’m trying to work with this script, but whenever i load the messages page in the current DOM, he doesn’t fill the second output div. So i think it will be an error by loading the DOM. when i set the link to rel=’external’  and when i have build a new page, it works. So do you have any idea to get the full message page into the current DOM? 

  • Bezmundo

    Great Tutorial, but i have a question. Say for example you wanted the three landmarks to be displayed in a list with only its name and then when you select the landmark of your choice it would then return another page with details. Ive so far got the new page to generate but I can’t get any details to load from passing over the id parameter. Any ideas on how to do this?

  • Patrick Qian

    Great article! I heard you used HTTPS in your apps, how do you handle self-signed SSL with PhoneGAP for iphone apps?

  • Hi Patrick,

    I’m afraid I’m not that savvy on self-signed SSL. Are you experiencing a particular issue?

    The resources that I’m currently accessing via HTTPS all work in the same way as via HTTP.

  • Abir

    HI Sam… THank you for this tuto.
    I’m new in phonegap. I’ve modified the url in the js for a simple Restful WS URL ( http://MY_IP:8080/RestProvider/message) , and it did not work. It returns zero as a status.

    Any Help please

  • Hansen

    Hi :) I use your example to add Markers to a map, and it works great. However, when I try to access the items from a function, (function inside a function) i get TypeError: ‘undefined’ is not an object. How do I access the json result? Thanks

  • Pingback: My article for Adobe’s Appliness magazine: Loading data into, and posting data from, a PhoneGap app()

  • Lesego Thekiso

    thank you so much for this, i have not used it yet, but i had a similar idea but was not too sure ifi would get it right.

  • You’re welcome. Check my recent article that shows loading and posting –

  • Tristan Dichoso

    Hi Sam, is there an Android version of that script?

  • Hi Tristan. The js/html remains the same for Android. If you create an Android PhoneGap app, just drop these files in and they will work. You just need to make you’re using the correct version of phonegap/cordova.js and are referencing it in your html.

    You can view a more recent version of this technique in my latest article -

  • Tristan Dichoso

    Great! Thanks Sam for that wonderful tutorial. Really helps.

    Thumbs up ^_^

  • Juninho De Luca

    Really great article!
    Id starting to learning about Obj C to be able to build apps loading data from mysql.
    So… I found your article and… voilá… a new world just opened.
    Thanks by share your experience!
    Sorry my bad english… I am from Brasil

  • Hi, is there any way I can use each element differently within the JSON querie using php?
    Possibly using json_decode ??

    Have you tried anything like that with this?

  • Hi Joel,

    I’m not sure what you mean, could you elaborate a bit further?

  • Eric

    Thanks a lot for this wonderful information. I’m able to get the json object using jquery .ajax as you’ve shown (the json object is visible inside my response if debug with firebug). However the contents don’t show up on the html page as I would expect them to between and tags. Does one need any format conversions to make this happen. What should I check to ensure the html output is displayed?

  • Hi Eric,

    Are there any errors showing in Firebug that relate to your script? Such an error might have occurred after the json object has been retrieved. Feel free to share a snippet and I’ll have a look if you like.

    – Sam

  • kiran

    hats off……….

  • JiaJun

    Hi, can this work for android? :D

  • Absolutely. Just use the html and js in your Android project and this will work.

  • JiaJun

    Hey Sam! Is there an Android Version for this?? I am trying out on android.

  • JiaJun

    Currently using Phonegap version 2.2, and did not modify any of the code however it didn’t work. The android emulator gave me a blank screen. Is it possible to send u a zip file to let you to check on what i did wrong? :)

  • Hmm unable to work, my android emulator gave me an empty screen, did not modify any of the code. Really need it to work soon. Will it be possible to send you a zip file of what i have done?

  • Its solved, hats off to you :)

  • anushka

    hii sam your tutorial is really goog but i am getting error in logcat stating that

    XMLHttpRequest cannot load Origin null is not allowed by Access-Control-Allow-Origin. at null:1

  • anushka

    thanks for your code it is a great help in my final year project . thanks a lot

  • Pingback: Phone Gap | Afstudeerstage @ TAXI Ams()

  • Mike

    I’ve been looking everywhere for something simple like this. But it returns three copies of each info set. Any ideas?

  • Hi Mike,

    Want to share your code? Post a link to a if you like.

    – Sam

  • Hi Anushka,

    Only just seen this comment. Are you using the jsonp callback correctly? Do you have your localhost listed as an external host?

    – Sam

  • Mike

    My code keeps returning the data three times. Any ideas?

  • csmith

    Hi, thanks for your tutorial. However, I couldn’t find ExternalHosts in the latest version of PhoneGap 2.4.0 I believe. Could you please indicate where to make these modifications.


  • Hey,

    Yep, looks like things have slightly changed with external hosts now. See the 2.4 details for domain whitelisting here

    “The whitelisting rules are found in AppName/config.xml and declared with the element .”

    Hope that gets things going!

  • RM

    Where is de GET variable jsoncallback send?

    A json in this way is correct:

    jsoncallback({“posicion”:”17″,”clasificacion”:”D 2014.”,”partidos_jugados_equipo”:”26″,”total_partidos_equipo”:”26″,”partidos_jugados”:”364″,”total_partidos”:”364″});

  • RM

    Sorry… like this

    jsoncallback({“posicion”:”17″,”clasificacion”:”D 2014.”,”partidos_jugados_equipo”:”26″,”total_partidos_equipo”:”26″,”partidos_jugados”:”364″,”total_partidos”:”364″});

  • I’m not sure what you’re asking…

    The jsoncallback parameter is automatically appended to the url you are requesting. It will be a random string like “jsoncallback=jQuery1504110298187006265_1364844570928”. You can see it if you open your javascript console and view the network tab when you call the ajax function.

    You can access this in your php (or other server side code) by checking the jsoncallback parameter – $_GET[“jsoncallback”]. This value must then wrap around the json response.

    I hope that helps?

  • art

    I came across this tutorial a bit late but i think i may have found a “temporarly” solution to the CORS xhr cross domain limitation in a “file://” context.

    Indeed for people who does not want to use JSONP but a pure XMLHttpRequest object in order to exchanges variables between a html file (with no apache context) and a php remote script and resolve this error message:

    “Origin null is not allowed by Access-Control-Allow-Origin”

    Simply put this php header snippet in the remote server file:

    <?php header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);

    Instead of header('Access-Control-Allow-Origin: *');

  • art

    header(‘Access-Control-Allow-Origin: ‘.$_SERVER[‘HTTP_ORIGIN’]);

    Instead of : header(‘Access-Control-Allow-Origin: *’);

  • nel

    thanks it is very easy to understand

  • Clifford

    Hi Sam

    If I use your php file as the URL in my version of load-json.js my app works. If I use a local database with exactly the same structure and a local php file referencing my database I get an error. My php file looks exactly like yours except it connects to a local DB. If I open my local php file in Firefox it gives me the error “…Undefined index: jsoncallback…” I am developing for android and using cordova 2.6.0, jquery 1.9.1, apache 2.4.2, MySQL 5.5.27 and PHP 5.4.6.

    Please point me in the right direction.


  • Clifford

    An additional comment – my local server is whitelisted (as is yours) and my php file returns the correct data from MySQL only with the error.

  • Hi Clifford,

    You will see this error if you access the php file in your browser unless you provide the jsoncallback parameter in your url request. This parameter is added on line 12 of load-json.js

    Essentially the ajax function appends this parameter and an arbitrary value to the url, automatically. So when you access the php file in your browser you would need to give the jsoncallback parameter a value. Something like…


    This will eliminate the error while accessing the file directly in your browser.

  • Clifford

    Thanks Sam, I eventually figured out the problem I was having displaying the output correctly in my browser by providing the jsoncallback parameter in my url (I subsequently read your response).

    But I still have a problem when it comes to the mobile app. If I specify your url for the php file it works fine and dandy, but as soon as I point to my local php script (using the code url: ‘’,) I get an error in the app. Despite the fact that my local script works perfectly in my browser now. Should I reference the local PHP file in a different way? I am working in Eclipse.

    PS. If I compare the logcat file for the working and non-working versions of the app there are no real differences and nothing that would point me to the source of the error. Is there any other way of getting more information on the error? I have looked at your post on native notifications for phonegap cordova apps.

  • Clifford

    Eventually found the solution – is the Android emulator’s own loopback interface. Need to use instead which is an alias to the host’s loopback interface.

  • Pat

    Is the code free to use for commercial purposes?

  • Hi Pat, absolutely – it’s free to use.

  • harshendrak

    Hi Sam

    Thanks for the nice post. I have a question about handling pages inside app. Please help me here.

    I am developing IPhone app using phonegap+Webservice(PHP+Mysql).
    Default login page appears. After successful login user will get
    dashboard section with Search Product, Add new product, Send message
    ,Inbox button. Contact Us etc…
    I have created all the forms in side
    index.html. By default login form visible. After login I am hiding
    login form & enabling dashboard form. Based on user click i show
    respective section and hide the other sections.

    Is there any way I can create individual page for each action like login, dashboard , add product, send message ,contact us etc.

    If yes how to redirect to new page when certain action happened. For
    example if login is successful how can i open dashboard.html & so

    Thanks & Regards

  • harshendrak

    Hi Sam

    I have question on Phonegap page architecture.

    I am developing Iphone App using phoneGap. App contains login page, dashboard, Product category list, Listing products under each category, View product details, Send message. Basically around 10 diffrent data sections.

    Can you please help me on the architectures seclection. What is the best approach,
    single-page application model OR Multi-page client-side application architectures ? Please suggest.

  • Hi Harshendrak,

    In my opinion it depends on the complexity.

    You could create a single page app, without using a framework, and toggle the visibility of each section accordingly. This is simple enough if the app is fairly straightforward.

    If you’re relying on lots of data models then something like Backbone would be useful.

  • Michael Hulsey

    Thanks for the article Sam. I am a relative newbie. I have a Jquery/PhoneGap app for ios that i have designed. I would like to populate a listview with links from an external file that is updated once a week. How would you approach that. Would you still create a mySql to contain the data. Thanks ahead of time for your response and any help.

  • Hi Michael,

    Yeah, I’d create a database to hold all of the data you intend to update and then use the method in this article to load a json output of the relevant table/columns. There is a more recent version of this method – – that might be better to refer to.

  • Michael Hulsey

    I kinda thought so…. I guess I was hoping to populate the listview from a text or XML file. Thanks again Sam.

  • There is nothing stopping you from doing that Michael. You could easily do this with an XML file. JSON is the same thing, just easier to read and manage(imo).

    The benefit of a database is that you don’t have to manually update a file and keep track of it etc. It just keeps things organised/centralised.

  • Mirco Ceccarini

    hello, I replaced the url of the php file …. but the file is not loaded .. there are other settings that should immediately be set?
    I am using PhoneGap 2.8.1
    hello and thank you in advance ..

  • New PhoneGap developer

    I want to thank you so much, I’ve been looking for how to do this for 2 days now. i’m a php web app developer and i just started using phonegap to build native applications for iOS. i needed a way ro get the content of a remote database into html5.

    Thanks mate.

  • Glad it was useful to you fella.

  • VicM

    Sam, this is gold! After 6 hours of searching and trying tons of configurations and code modifications I could finally could send and receive my JSON data correctly because you generously wrote this article. You save me from wasting more time and getting frustrated. I am not sure why if this things are widely used it is so difficult to get valuable and kindly explained articles like this.

  • Thanks VicM, glad you found it useful.

  • Howie

    Hi Guys.

    I’m using the PhoneGap build service in Dreamweaver in CS6 and am following the code below. When I create and preview the App in my iPhone the external data won’t load. It loads in the browser but not within the App. Its being blocked from loading. I tried adding the domain to the config xml under

    &lt;access origin=&quot;; /&gt;

    In my account I can see the app I built thru Dreamweaver but cant see how to whitelist a domain. I am trying to get data from a mysql db attached to the domain.
    Any ideas? I’m a newbie.


  • Arjun Dhiman

    How i do auto sync using this on my phone. I want the phone to automatically update every time i insert/edit the database.

  • Pingback: Cordova app timeout when connecting to local server using ajax | Technology & Programming()

  • David Devane

    Does this work? trying to do the same thing

  • Tony

    Great Post! Having one issue where the info is displaying twice. Once as a json output with ([{“id”:”1″,”big ben….. etc and then the nicer format below that with the same information. how do I stop that?

  • Zach

    I had so much trouble with some of these concepts and this post was invaluable. THANK YOU!

  • Sunil P

    I m new to PhoneGap APP, I want to display latitude and longitude values taking from URL and pass those with JSON object and display that locations on google map.
    Plz can anyone help me out.
    Thanks in advance.

  • DanTheMan

    Hi Sam

    I hope you are still getting these comments as Im stuck for WEEKS..

    Android perfectly in browser to remote Db on mydomanin..ive whitelisted and given internet access but always get an error msg of ‘There was an error loading the data’..Im stumped…please help..

    my code


    $(document).bind(“mobileinit”, function() {
    $.support.cors = true;
    $.mobile.allowCrossDomainPages = true;

    var output = $(‘#mylbl’);
    url: ‘’,
    dataType: ‘jsonp’,
    jsonp: ‘jsoncallback’,
    timeout: 5000,
    success: function(data, status){
    $.each(data, function(i,item){
    var contact = ””
    + ”+item.address+”;
    error: function(){
    output.text(‘There was an error loading the data.’);




    Can you advise?
    Could it be phonegap version issues?

    Have developibg using local storages apps no problem

  • There shouldn’t be an issue if it’s working fine in your browser. Do you have the internet permission in your AndroidManifest.xml?

    What do the console logs say in Eclipse? They’re a bit verbose, but usually you can see exactly where the problem is after a bit of scrolling.

    You’re using quite an old version of Phonegap (1.2.0) – they’re up to version 3.3.0 now. I’d try with the most recent version and see if that gets things moving.

  • DanTheMan

    Hi Sam, Thanks for getting back.
    I’m actually using v 3.1 phonegap but was referencing v 1.2…ooops
    Amended that and ….. zilch …
    The battle goes on :-(

  • How about the internet permission and the Eclipse console logs?

  • DanTheMan

    Internet permissions YES
    Console logs show nothing just application loading but no content shows either in emulator or if I send apk to my phone..just the error loading the data msg.
    Mind you I was getting no error msg until I referenced local copy of phonegap rather than the CDN so I’m inclined to think its an internet connection issue…
    Im really grateful for your responses Sam as I’ve struggled with this…
    Once I can resolve this I can move on with projects I’m hoping to undertake..

  • Ok, something else to try; within the success function, comment everything out and just have


    check the console log to see if anything is being loaded.

    For better error reporting, change the error function to something like:

    error: function(jqXHR, textStatus, errorThrown) {
    console.log(textStatus, errorThrown);

    And check the console to see what is going on.

  • DanTheMan

    Thanks Sam,
    I’ll have a go this evening as dev machine is at home…

  • DanTheMan

    Hi Sam,
    Finally got this working but only after I whitelisted “*” – I had “.*” there instead….really not sure why this is and as far as I know I shouldn’t leave “*” there except for development?
    Anyhow I’ll plough on…..many thanks

  • Excellent. I did think “.*” looked a bit strange, but noticed that’s how they have it in the PhoneGap documentation. Good to know :)

  • Pingback: Using CodeIgniter as the backend for PhoneGap app developing | Portfolio - YOYU()

  • Andrew

    Nice.. I am very near to begin to learn really this tech.. but will work with ASP classic? i dont know php but i can do anything in asp and database and javascript… thanks

  • Shan

    Hi Sam, Thanks for great post. My question is – multiple images stored in database. only the names are stored. and images location is in a folder on server. how can I display one image from database?


  • suranka
  • suranka
  • Emaseamase

    Do this code in XDK too? I find problem connecting to the database and retrieving the data.

  • Emaseamase

    Do this codes work in XDK too? I find problem connecting to the database and retrieving the data.