Sam Croft

A designer/developer on HTML, CSS, JavaScript and PhoneGap

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

  • 191 comments

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.

$.ajax({
	url: 'http://yourdomain.com/your-data-request.php?foo=bar',
	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' (
	'id' int(11) NOT NULL AUTO_INCREMENT,
	'name' varchar(50) DEFAULT NULL,
	'lat' decimal(18,12) DEFAULT NULL,
	'long' decimal(18,12) DEFAULT NULL,
	PRIMARY KEY ('id')
)

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.

<?php
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[] = $row;
}

mysql_close($con);

echo $_GET['jsoncallback'] . '(' . 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.

$(document).ready(function(){
	var output = $('#output');
	
	$.ajax({
		url: 'landmarks.php',
		dataType: 'jsonp',
		jsonp: 'jsoncallback',
		timeout: 5000,
		success: function(data, status){
			$.each(data, function(i,item){ 
				var landmark = '<h1>'+item.name+'</h1>'
				+ '<p>'+item.latitude+'<br>'
				+ item.longitude+'</p>';
				
				output.append(landmark);
			});
		},
		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 samcroft.co.uk 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 thirtysomething designer/developer and co-founder of Running in the Halls Ltd—a web and app development studio in Huddersfield, UK. I was educated in graphic design and now specialise in front-end web and app development; my main passion being usability and accessibility. I strongly believe web apps (vs native) are the future and love developing for mobile using the wonderful PhoneGap.

I am a massive sports fan - Formula One in particular. I live in the Pennines with my beautiful wife, Alex. Occasionally I own a large scruffy beard.

I tweet about all of my interests - you should follow me. I also have a .

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

  • http://dilsayar.com dilsayar

    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 ;)

    Cheers!

  • 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,
    Best,
    Jérôme.

  • Sam Croft

    Hi Matt/Jérôme,

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

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

    ‘+item.name+’


    + ‘

    ‘+item.latitude+’

    + item.longitude+’

    ‘;

    output.append(landmark);
    });
    }
    });

    Very similar, but using jQuery.post() instead http://api.jquery.com/jQuery.post/

    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.

    Russell

  • 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>’+item.name+'</h1>’
    + ‘<p>’+item.latitude+'<br>’
    + item.longitude+'</p>’ + ”;

    output.append(landmark);
    });

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

    I hope this helps. Best of luck :)

  • Russell Barber

    Cheers

  • 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 :)

  • http://www.facebook.com/profile.php?id=1075004383 Alex Youcef Saidani

    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? http://wiki.phonegap.com/w/page/42243680/Upgrading%20your%20iOS%20PhoneGap%20Project 

    “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.

  • http://www.facebook.com/profile.php?id=1075004383 Alex Youcef Saidani

    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

    Thanks

  • 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.

  • http://twitter.com/mtvanb Menno van Bohemen

    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 http://api.jquery.com/jQuery.get/

    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 http://api.jquery.com/jQuery.get/ 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 = 'email@email.com';$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 http://www.leyendeckers.com/parser.php

  • 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(“http://yourdomain.com/email.php”, { name: “John”, message: “Hello” } );

    Is the same as:

    http://yourdomain.com/email.php?name=john&message=hello

    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(“http://yourdomain.com/parser.php”, { ??? } );                });               });                   

  • 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.

    http://api.jquery.com/serialize/

    So you would have something like;

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

  • http://www.facebook.com/profile.php?id=100001234504868 Simon Bresch

    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() {
     
    alert($(this).serialize());
     
    return false;});});

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

    $(document).ready(function() {

    $(‘form’).submit(function(){

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

    alert(sendthis);

    $.ajax({

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

    data: sendthis,

    success: function(){

    console.log(‘sent!’);

    },error:function{console.log(‘ERROR!’);}});});});

  • 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; });

  • http://www.facebook.com/profile.php?id=100000950573420 Benevalter Bento Jr

    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.

    bye

  • Simon

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

  • http://twitter.com/moyado moyado

    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

    Heya,

    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: item.name });});

  • 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

    Hi,

    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.

    thx,

  • 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…

  • http://www.jpk.in/ Jithesh Pk

    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:

    setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

          #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’);

    $STH->setFetchMode(PDO::FETCH_ASSOC);

        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.
    Thanks!

  • Sam Croft

    Hi,

    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

    Cheers!!

  • 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!

  • http://twitter.com/iBoedel iBoedel

    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

  • http://samcroft.co.uk/ Sam Croft

    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.

    Craig

  • http://samcroft.co.uk/ Sam Croft

    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 :)

  • http://twitter.com/iBoedel iBoedel

    Yes, there was the content header json

    but the problem relies in my cors settings (http://enable-cors.org/)
    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.

  • http://samcroft.co.uk/ Sam Croft

    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?

  • http://samcroft.co.uk/ Sam Croft

    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 http://groups.google.com/group/phonegap

    For PhoneGap in general I recommend giving Jonathan Stark’s Building iPhone Apps with PhoneGap a read http://ofps.oreilly.com/titles/9780596805784/ – 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.id+’ ‘ + ‘‘+item.question+’
                        ”+item.answera+”
                        +item.answerb+”
                        +item.answerc+”
                        +item.answerd+”;

  • http://samcroft.co.uk/ Sam Croft

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

    http://jsfiddle.net/6uX7Q/

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

    http://jsfiddle.net/E5svs/1/

    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.

    Thanks.

     

  • 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”…

  • http://samcroft.co.uk/ Sam Croft

    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 yourdomain.com). 

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

    – Sam

  • http://samcroft.co.uk/ Sam Croft

    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…

  • http://samcroft.co.uk/ Sam Croft

    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 – http://www.neotericdesign.com/blog/checking-the-online-status-with-phonegap-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.

    Thanks,

    Nick

  • http://samcroft.co.uk/ Sam Croft

    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 “http://samcroft.co.uk/demos/updated-load-data-into-phonegap/landmarks.php” could access the data in your database without having app or any database passwords

  • http://samcroft.co.uk/ Sam Croft

    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

  • http://twitter.com/shaharsol Shahar Solomianik

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

  • Renux

    Hi!
    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: ‘http://renux.16mb.com/phonegap/landmarks.php’, 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.’); } }); /*});*/});

    thanx!!

  • 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: ‘http://renux.16mb.com/phonegap/landmarks.php’, 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.’); } }); /*});*/});

  • http://samcroft.co.uk/ Sam Croft

    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() {

                    //alert(“appReady()”);
                    $.ajax({
                        url: ‘http://192.168.0.92/TLGVUAT/Tlgvwebservice.php?user=TLGVUat&password=TLGVUat&reqparam=N’,

                            dataType: ‘json’,

                            jsonp: ‘callback’,
                           error: function(XMLHttpRequest, textStatus, errorThrown) {
                                alert(‘Failure’);
                            },
                            success: function(data) {
                                alert(“Success..!1″);  
                                $(‘#non’).html(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
     avinashnv2@gmail.com

  • 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

  • http://samcroft.co.uk/ Sam Croft

    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
    onDeviceReady()
    });
    // 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
                                             onDeviceReady()
                                             });
                            // Your main code
                            });

  • Craig

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

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

  • http://samcroft.co.uk/ Sam Croft

    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
                                                onDeviceReady()
                                                });

    var output = $(‘#output’); $.ajax({ url: ‘http://samcroft.co.uk/demos/updated-load-data-into-phonegap/landmarks.php’, dataType: ‘jsonp’, jsonp: ‘jsoncallback’, timeout: 5000, success: function(data, status){ $.each(data, function(i,item){ var landmark = ”+item.name+” + ”+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.

    Thanks

    Dan

  • http://samcroft.co.uk/ Sam Croft

    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 
    Ranjith

  • http://samcroft.co.uk/ Sam Croft

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

  • http://samcroft.co.uk/ Sam Croft

    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 http://think2loud.com/224-reading-xml-with-jquery/

    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.

  • http://samcroft.co.uk/ Sam Croft

    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.

  • http://samcroft.co.uk/ Sam Croft

    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 phonegap.com/download 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?

  • http://samcroft.co.uk/ Sam Croft

    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:
        $.ajax({
            url: ‘nachrichten.php’,
            dataType: ‘jsonp’,
            jsonp: ‘jsoncallback’,
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){
                    var nachricht = ”+item.headline+”
                    + ‘‘+item.date+’
                    + item.teaser+”;
                
                    output.append(nachricht);
                });
            },
            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?

  • http://samcroft.co.uk/ Sam Croft

    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

  • http://samcroft.co.uk/ Sam Croft

    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=”‘+item.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
        
            
            
                Nachrichten
                    
        
        
            Fußzeile
        

        
            Home
            Nachrichten
        
            
                    
        
        
            Fußzeile
        

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

        $.ajax({
            url: ‘app/nachrichten.php’,
            dataType: ‘jsonp’,
            jsonp: ‘jsoncallback’,
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){
                    if(item.id == nachrichtid) {
                        var nachricht = ”+item.headline+”
                        + ‘‘+item.date+’
                        + item.text+”;
                
                        output.append(nachricht);
                    }    
                });
            },
            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?

  • http://samcroft.co.uk/ Sam Croft

    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.

  • http://samcroft.co.uk/ Sam Croft

    You’re welcome. Check my recent article that shows loading and posting – http://samcroft.co.uk/2012/my-article-for-adobes-appliness-magazine-data-in-phonegap-apps/

  • Tristan Dichoso

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

  • http://samcroft.co.uk/ Sam Croft

    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 -http://samcroft.co.uk/2012/my-article-for-adobes-appliness-magazine-data-in-phonegap-apps/

  • 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

  • http://twitter.com/joelseneque Joel Seneque

    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?

  • http://samcroft.co.uk/ Sam Croft

    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?

  • http://samcroft.co.uk/ Sam Croft

    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 jsfiddle.net snippet and I’ll have a look if you like.

    – Sam

  • kiran

    hats off……….

  • JiaJun

    Hi, can this work for android? :D

  • http://samcroft.co.uk/ Sam Croft

    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? :)

  • http://www.facebook.com/jiajun.basketballaddict JiaJun BasketballAddict

    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?

  • http://www.facebook.com/jiajun.basketballaddict JiaJun BasketballAddict

    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 http://127.0.0.1:49845/fb1fc049-78f9-4373-9599-70b0f0aacad2. 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?

  • http://samcroft.co.uk/ Sam Croft

    Hi Mike,

    Want to share your code? Post a link to a http://jsfiddle.net/ if you like.

    – Sam

  • http://samcroft.co.uk/ Sam Croft

    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.

    Best,

  • http://samcroft.co.uk/ Sam Croft

    Hey,

    Yep, looks like things have slightly changed with external hosts now. See the 2.4 details for domain whitelisting here http://cordova.apache.org/docs/en/2.4.0/guide_whitelist_index.md.html

    “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″});

  • http://samcroft.co.uk/ Sam Croft

    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.

    Thanks!

  • 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.

  • http://samcroft.co.uk/ Sam Croft

    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

    https://github.com/samcroft/Loading-data-into-PhoneGap/blob/master/iOS%20app/Cordova-1.7.0%2B/Loading%20data%20in%20Cordova/www/js/load-json.js#L12

    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…

    your-source.php?jsoncallback=1234

    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: ‘http://127.0.0.1/landmarks.php’,) 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 – 127.0.0.1 is the Android emulator’s own loopback interface. Need to use 10.0.2.2 instead which is an alias to the host’s loopback interface. http://developer.android.com/tools/devices/emulator.html#networkaddresses

  • Pat

    Is the code free to use for commercial purposes?

  • http://samcroft.co.uk/ Sam Croft

    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
    on.

    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.

  • http://samcroft.co.uk/ Sam Croft

    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.

  • http://samcroft.co.uk/ Sam Croft

    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 – http://samcroft.co.uk/2012/my-article-for-adobes-appliness-magazine-data-in-phonegap-apps/ – 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.

  • http://samcroft.co.uk/ Sam Croft

    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.

  • http://samcroft.co.uk/ Sam Croft

    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.

  • http://samcroft.co.uk/ Sam Croft

    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;http://www.mysite.com&quot; /&gt;

    In my https://build.phonegap.com/ 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 mysite.com domain.
    Any ideas? I’m a newbie.

    Thanks

  • 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

    Hi,
    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 APP..work 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

    mydownload

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

    $(document).ready(function(){
    var output = $(‘#mylbl’);
    $.ajax({
    url: ‘http://www.mydomain.com/landmarks1.php’,
    dataType: ‘jsonp’,
    jsonp: ‘jsoncallback’,
    timeout: 5000,
    success: function(data, status){
    $.each(data, function(i,item){
    var contact = ”+item.name+”
    + ”+item.address+”;
    output.append(contact);
    });
    },
    error: function(){
    output.text(‘There was an error loading the data.’);
    }
    });
    });

    Details

    PHP

    Whitelisting:

    Can you advise?
    Could it be phonegap version issues?

    Have developibg using local storages apps no problem

  • http://samcroft.co.uk/ Sam Croft

    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 :-(

  • http://samcroft.co.uk/ Sam Croft

    How about the internet permission and the Eclipse console logs?

  • DanTheMan

    Hi
    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..
    regards

  • http://samcroft.co.uk/ Sam Croft

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

    console.log(data);

    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…
    regards

  • 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
    Sean

  • http://samcroft.co.uk/ Sam Croft

    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?

    Thanks.