
PHP and MySQL are most popular backend technologies ever. 82% of mobile apps using PHP and MySQL as their backend server. In this tutorial we will see how to create PHP web services and call them using Intel XDK. And also how to execute MySQL queries using Intel XDK.
Introduction to Web Services
A web service is a method of communication between two process over a network. REST web services are those web services which use HTTP to communicate over the network. Some popular REST web service request and response formats are SOAP, JSON, XML, XML-RPC etc.
SOAP, JSON, XML etc formats are used to request or send some data to an remote application. Whereas XML-RPC format is used when you want to call a function of a remote application.
Create a JSON REST Web Service using PHP
Let’s create a REST web service which uses JSON format to send some requested data.
Here is an PHP code which sends an PHP array as JSON object to the Intel XDK app
{
//checks the format client wants
if($_GET["names"] == "json")
{
$name_and_age = array("Name1" => 12, "Name2" => 34, "Name3" => 67);
//sets the response format type
header("Content-Type: application/json");
//converts any PHP type to JSON string
echo json_encode($name_and_age);
}
else
{
//web service not found
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
Success output would be
Above we created a HTTP GET web service but you can also create POST, DELETE, PUT etc web services. POST is used if you want to send data to server.
If web service is not found then we are sending 404 not found header in response. There are various HTTP response status codes available for use in various different cases. Here is the list
101 - "Switching Protocols",
200 - "OK",
201 - "Created",
202 - "Accepted",
203 - "Non-Authoritative Information",
204 - "No Content",
205 - "Reset Content",
206 - "Partial Content",
300 - "Multiple Choices",
301 - "Moved Permanently",
302 - "Found",
303 - "See Other",
304 - "Not Modified",
305 - "Use Proxy",
306 - "(Unused)",
307 - "Temporary Redirect",
400 - "Bad Request",
401 - "Unauthorized",
402 - "Payment Required",
403 - "Forbidden",
404 - "Not Found",
405 - "Method Not Allowed",
406 - "Not Acceptable",
407 - "Proxy Authentication Required",
408 - "Request Timeout",
409 - "Conflict",
410 - "Gone",
411 - "Length Required",
412 - "Precondition Failed",
413 - "Request Entity Too Large",
414 - "Request-URI Too Long",
415 - "Unsupported Media Type",
416 - "Requested Range Not Satisfiable",
417 - "Expectation Failed",
500 - "Internal Server Error",
501 - "Not Implemented",
502 - "Bad Gateway",
503 - "Service Unavailable",
504 - "Gateway Timeout",
505 - "HTTP Version Not Supported"
Here is how you can make a request to the web service using JavaScript running in XDK
xhr.open("GET", "http://domain/?names=json", false);
xhr.onload = function(){
if(xhr.status == 200)
{
var json_string = xhr.responseText;
var json = JSON.parse(json_string);
intel.xdk.notification.alert(json.Name1, "Name 1");
}
else if(xhr.status == 404)
{
intel.xdk.notification.alert("Web Service Doesn't Exist", "Error");
}
else
{
intel.xdk.notification.alert("Unknown error occured while connecting to server", "Error");
}
}
xhr.send();
Intel XDK doesn’t have any AJAX Same Origin Policy therefore you can make a AJAX request to any domain of your wish.
Output in APP would be
Running MySQL Queries using XDK
There is no way to directly connect and query MySQL using XDK. If you want to directly connect and query MySQL then you have to write your own XDK plugin which can send MySQL protocol requests.
Developers use web services as a mid layer to communicate with MySQL. Here is an example PHP web service which retrieves all the rows of a table and returns to the client i.e., XDK,
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("host", "username", "password", "db_name");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT * FROM wp_users";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
$jsonData[] = $row;
}
/* free result set */
mysqli_free_result($result);
//encode to JSON format
echo "{"rows":". json_encode($jsonData) . "}";
}
else {
echo "{"rows":". json_encode($jsonData) . "}";
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
Sample output would be
Here rows are output as JavaScript multidimensional array. Here also we are using JSON format.
Here is how you can make a request to the web service using JavaScript running in XDK
xhr.open("GET", "http://domain?get_rows=json", false);
xhr.onload = function(){
alert(xhr.responseText);
if(xhr.status == 200)
{
var json_string = xhr.responseText;
var json = JSON.parse(json_string);
intel.xdk.notification.alert(json.rows[0][0], "Name 1");
}
else if(xhr.status == 404)
{
intel.xdk.notification.alert("Web Service Doesn't Exist", "Error");
}
else
{
intel.xdk.notification.alert("Unknown error occured while connecting to server", "Error");
}
}
xhr.send();
Conclusion
We saw how to create web services using PHP which can be consumed by XDK. We also saw how to use web services to talk to MySQL. You can go ahead and build a REST POST web service to upload some file or send some kind of data to server for storage or any other purpose.