Blog Post Icon
Blog
03/04/2015

Pull JSON data from your website to your mobile application with Ajax and PHP

Hello!

Making mobile applications is much easier than it used to be. As with previous posts, we have been experimenting with Apache Cordova Framework for easily building mobile applications, leveraging web frameworks like AngularJS.

Many mobile applications communicate with a centralized “server” or website that retains all the data that may be useful for the mobile app. For example you might want to have a mobile application that retains a centralized “friends list” that the end-user can modify. You can store this friends list in a database, and access that data by making an Ajax request to pull the data in json format.

For the website that retains and manages this data, we have decided (for this example) to use the PHP Slim Framework. We mainly chose this because it makes rolling out a web based application API with a database backend very simple (in under 30-50 lines of code).

For the PHP website portion of this example, we will establish a GET path that makes a simple mysql database query and returns that data after you access the API with a web request. First we want to create a simple database table to hold the data :

CREATE TABLE IF NOT EXISTS `friends` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)
);

The above mysql query simply creates a table called “friends” to store some information for friends such as name ,email and the date/time that the entry was created. Next we want to install the PHP Slim framework and create a simple Slim app that receives a request for /friends , does a mysql query and then returns the json response.

get('/friends', 'getfriends');

$friends->run();

// ****************
// CUSTOM FUNCTIONS
// ****************

function getfriends() {
        $sql = "SELECT * from friends order by created_at DESC;";
        try {
                $db = connect_db();
                $result = $db->query($sql);
                while ( $row = $result->fetch_array(MYSQLI_ASSOC) ) {
                        $data[] = $row;
                }
                $db = NULL;
                echo json_encode($data);
        } catch(PDOException $e) {
                echo '{"error":{"text":'. $e->getMessage() .'}}';
        }
}

Whats happening here? Well there is quite a bit of documentation on the PHP Slim framework, but for any moderately experienced developer the above code is straightforward. The framework listens for a request to the URI “/friends” and then executes the SQL query and spits out the result.

We now have a very simple website that has a very simple API to interact with! When you actually make the query in your browser, you will see a JSON response similar to something like the following :

[{"id":"1","name":"john smith","email":"some@email.com","status":"1","created_at":"2015-02-20 17:24:01"},
{"id":"1","name":"jane smith","email":"other@email.com","status":"1","created_at":"2015-02-21 17:24:01"}]

Now in the mobile application we want to make an AJAX query to execute the GET request and store the data in an array so we can use that data in our mobile application!

$.getJSON('http://your-site/friends', function(data) {
        $.each(data, function(index) {
            alert(data[index].name);
        });
    });

The getJSON query simply connects to your site, and parses the json data into an array. Then you can do whatever you want with that data in your mobile app – put it in a list, table or anything you want.

You can also accept POST requests to reverse the flow of data. If you want to implement the ability for your IOS or Android application to make changes to said friends lists, then you could accept a post request to the PHP Slim framework from your mobile app. Then the data could be received, processed and stored as an UPDATE or INSERT query into the mysql database.

Next post I’ll be going into security considerations with these types of activities, including implementing an API key authentication to secure your data and only allow authorized parties to make these types of queries. Implementing SSL encryption, authentication host headers and additional host headers to have API key validation is important and part of a set of best practices in order to secure your systems end-to-end.

At Shift8, we cater to all sorts of businesses in and around Toronto from small, medium, large and enterprise projects. We are comfortable adapting to your existing processes and try our best to compliment communication and collaboration to the point where every step of the way is as efficient as possible.

Our projects are typically broken into 5 or 6 key “milestones” which focus heavily on the design collaboration in the early stages. We mock-up any interactive or unique page within your new website so that you get a clear picture of exactly how your design vision will be translated into a functional website.

Using tools like Basecamp and Redpen, we try to make the process simple yet fun and effective. We will revise your vision as many times as necessary until you are 100% happy, before moving to the functional, content integration and development phases of the project.

For the projects that are more development heavy, we make sure a considerable amount of effort is spent in the preliminary stages of project planning. We strongly believe that full transparency with a project development plan ensures that expectations are met on both sides between us and the client. We want to ensure that the project is broken into intelligent phases with accurate budgetary and timeline breakdowns.

Approved design mock-ups get translated into a browse-ready project site where we revise again and again until you are satisfied. Client satisfaction is our lifeblood and main motivation. We aren’t happy until you are.

Need Web Design?

Fill out the form to get a free consultation.

shift8 web toronto – 416-479-0685
203A-116 geary ave. toronto, on M6H 4H1, Canada
© 2024. All Rights Reserved by Star Dot Hosting Inc.

contact us
phone: 416-479-0685
toll free: 1-866-932-9083 (press 1)
email: sales@shift8web.com

Shift8 Logo