terça-feira, 25 de fevereiro de 2014

Phonegap - jQuery Ajax Example With JSON Response

Hello,
In this tutorial you will learn how to connect a device running Phonegap with a server using jquery ajax and JSON. The tutorial is split up into two basic parts:-
  • Client side code
  • Server side code
Note:- This tutorial can be used in normal webpages too the exact same code.

Jquery ajax and json

Ajax is a method used transfer data between server and client without reloading the entire page. With the jquery ajaxframework, you can load XML , json, html etc data in the background using HTTP POST and GET methods. Jquery ajax methods makes ajax implementation a lot easier(Implementing ajax in browsers is a headache since you have to write different code for each browser ). Json is basically a language for representing objects, in other words it is a format used to carry data and  good alternative to XML.

Description of app

We will demonstrate Server – Client connection using a simple ajax app. There will be 2 buttons named cars and bikes. Clicking one of the buttons will fetch a list of cars or bikes from the server.
Prerequisites:-
  • An IDE with Phonegap installed(you should also have emulator installed and configured to run Phonegap code), please follow this guide if you haven’t done it already.
  • A server which can run php (version 5.2 or greater) , you could install Xampp or use a free hosting like Freehostia.

Section 1: Setting up Client Side User-Interface:

We need 2 buttons labeled “cars” and “bikes” the results will be displayed as a list. A function connect()  is used to send the Ajax request. Simply add the following inside your body tag. 
?
App UI HTML
1
2
3
4
5
<center><b>Bikes or Cars</b></center>
<center><input onclick="connect(this.value)" type="button" value="cars" /></center>
<center><input onclick="connect(this.value)" type="button" value="bikes" /></center>
<center><b>Results</b></center>
<ul id="result"></ul>
jquery ajax UI

Javascript (jquery ajax request):

Add this code to the head section of your index.html or html page.
?
The connect() Function
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
<script charset="utf&minus;8" type="text/javascript">
function connect(e)
{
var term= {button:e};
$.ajax({
type:'POST',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
alert(“no connection”);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});}
</script>
When one of the buttons are clicked the connect() function is used to send an ajax request to the server URL containing the PHP.
An Ajax call has many parameters:-
  • URL : The location of the php file on the server.(line 6)
  • type: The HTTP Request method in use either POST or GET.(line 7)
  • data: the data to be send via POST or GET.(line 8)
  • dataType: The data send back from the server. we are using JSON but common formats are XML, html, JSONP(line 9)
  • error: This function is called if an error occurs during connection.(line 10)
  • timeout: max time before request should be completed, specified in milliseconds.(line 12)
  • success: If all goes well this function is called.(line 13)
This function simply appends the data return from the server to an un-ordered list.

Section 2 : Setting up Server Side

Create a PHP file called reply.php and paste this code.
?
Server-Side PHP
1
2
3
4
5
6
7
<?php
$choice =$_POST["button"];
$cars = array(“Honde”, ”BMW” , ”Ferrari”);
$bikes = array(“Ducaite”, ”Royal Enfield” , ”Harley Davidson”);
if($choice == ”cars”) print json_encode($cars);
else print json_encode($bikes);
>
This PHP returns an array on line 8 or line 6 using “print json_encode” function. This skeleton can be used in all sorts of ways, you can write PHP code to connect to a SQL database etc and other cool stuff like creating a login, registration , streaming articles and other contents. You can also send images and other media using this method by changing the datatype.                                                                                   
jquery ajax: when car is clickedjquery ajax: when bike is clicked
Stay tune for more tutorials and articles :). Please feel free ask questions down in the comment section below. Thank You
Regards,
INdiageeks Team