Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Saturday, 24 January 2015

Create a restfull services using Slim PHP Framework

in that most the PHP methods got depreciated. I have been looking for a simple RESTful api framework in PHP, I found few lightweight frameworks called Slim and Epiphany. In this tutorial I had implement a sample user updates RESTful web services project using Slim framework in PHP, it is very simple to implement and only focused on RESTful.

The tutorial contains three folders called apijs and css with PHP files.
api
-- Slim // Slim Framework
---- db.php 
---- index.php // api index file
---- .htaccess // url redirection file. 
js
-- jquery.min.js
-- ajaxGetPost.js
css
-- style.css
index.html

Database Design
To build the friend updates system, you have to create three tables such as Users, Friends and Updates. You can check my previous tutorials for friend system.

Users Table
User table contains all the users registration details. 
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT,
`username` varchar(50),
`password` varchar(100),
`name` varchar(100),
`profile_pic` varchar(200),
PRIMARY KEY (`user_id`)
);

Updates Table
User table contains user status update details. 
CREATE TABLE `updates` (
`update_id` int(11) AUTO_INCREMENT,
`user_update` text,
`user_id_fk` int(11), 
`created` int(11),
`ip` varchar(50),
PRIMARY KEY (`update_id`)
);

RESTful Web Services API using Java and MySQL

Slim Framework

api/index.php
Slim Framework helps you to implement API system simple. 
<?php
require 'db.php';
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

$app = new \Slim\Slim();

$app->get('/users','getUsers');
$app->get('/updates','getUserUpdates');
$app->post('/updates', 'insertUpdate');
$app->delete('/updates/delete/:update_id','deleteUpdate');
$app->get('/users/search/:query','getUserSearch');

$app->run();

// GET http://www.yourwebsite.com/api/users
function getUsers() {
$sql = "SELECT user_id,username,name,profile_pic FROM users ORDER BY user_id DESC";
try {
$db = getDB();
$stmt = $db->query($sql); 
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"users": ' . json_encode($users) . '}';
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/phperror.log'); //Write error log
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

// GET http://www.yourwebsite.com/api/updates
function getUserUpdates() {
$sql = "SELECT A.user_id, A.username, A.name, A.profile_pic, B.update_id, B.user_update, B.created FROM users A, updates B WHERE A.user_id=B.user_id_fk  ORDER BY B.update_id DESC";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$updates = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"updates": ' . json_encode($updates) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

// DELETE http://www.yourwebsite.com/api/updates/delete/10
function deleteUpdate($update_id)
{
$sql = "DELETE FROM updates WHERE update_id=:update_id";
try {
$db = getDB();
$stmt = $db->prepare($sql); 
$stmt->bindParam("update_id", $update_id);
$stmt->execute();
$db = null;
echo true;
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

// POST http://www.yourwebsite.com/api/updates
function insertUpdate() {
//....
//....
}

function getUserUpdate($update_id) {
//.....
//.....
}

// GET http://www.yourwebsite.com/api/users/search/sri
function getUserSearch($query) {
//.....
//....
}
?>

db.php
You have to modify database configuration details, before trying this enable php_pdoextension in php.ini file.
<?php
function getDB() {
$dbhost="localhost";
$dbuser="username";
$dbpass="password";
$dbname="database";
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>

Chrome Extention
A Extention for testing PHP restful API response download here Advanced REST client Application

Cross Domain Access
A cross-domain system is transfer information/data between two or more differing domains. Eg. abc.com to xyz.com

.htaccess 
I did modified the Slim Framework default .htaccess code for cross domain support.
RewriteEngine On

# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

# Cross domain access
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUTGETPOSTDELETEOPTIONS"

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]


Jquery
Contains JavaScript and HTML code, using Jquery ajax parsing API data into HTML format.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="js/ajaxGetPost.js"></script>
<script>
$(document).ready(function()
{

var base_url="http://www.yourwebsite.com/project_name/";
var url,encodedata;
$("#update").focus();

/* Load Updates */
url=base_url+'api/updates';
ajax_data('GET',url, function(data)
{
$.each(data.updates, function(i,data)
{
var html="<div class='stbody' id='stbody"+data.update_id+"'><div class='stimg'><img src='"+data.profile_pic+"' class='stprofileimg'/></div><div class='sttext'><strong>"+data.name+"</strong>"+data.user_update+"<span id='"+data.update_id+"' class='stdelete'>Delete</span></div></div>";
$(html).appendTo("#mainContent");
});
});

/* Insert Update */
$('body').on("click",'.stpostbutton',function()
{
var update=$('#update').val();
encode=JSON.stringify({
        "user_update": update,
        "user_id": $('#user_id').val()
        });
url=base_url+'api/updates';
if(update.length>0)
{
post_ajax_data(url,encode, function(data)
{
$.each(data.updates, function(i,data)
{
var html="<div class='stbody' id='stbody"+data.update_id+"'><div class='stimg'><img src='"+data.profile_pic+"' class='stprofileimg'/></div><div class='sttext'><strong>"+data.name+"</strong>"+data.user_update+"<span id='"+data.update_id+"' class='stdelete'>Delete</span></div></div>";
$("#mainContent").prepend(html);
$('#update').val('').focus();
});
});
}

});

/* Delete Updates */
$('body').on("click",'.stdelete',function()
{
var ID=$(this).attr("id");
url=base_url+'api/updates/delete/'+ID;
ajax_data('DELETE',url, function(data)
{
$("#stbody"+ID).fadeOut("slow");
});
});

});
</script>

Create a RESTful services using Slim PHP Framework


HTML Code
Contains HTML code. $("body").on('click','.stpostbutton', function(){}stpostbutton is the ID name of the POST button. Using jquery stringify converting input data into JSON format.
<div>
<textarea id="update" class="stupdatebox"></textarea>
<input type="hidden" id="user_id" value="User Session Value">
<input type="submit" value="POST" class="stpostbutton">
</div>

<div id="mainContent"></div>


ajaxGetPost.js
Jquery Post, Get and Delete Ajax functions.
//POST Ajax
function post_ajax_data(url, encodedata, success)
{
$.ajax({
type:"POST",
url:url,
data :encodedata,
dataType:"json",
restful:true,
contentType: 'application/json',
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}

//GET and DELETE Ajax
function ajax_data(type, url, success)
{
$.ajax({
type:type,
url:url,
dataType:"json",
restful:true,
cache:false,
timeout:20000,
async:true,
beforeSend :function(data) { },
success:function(data){
success.call(this, data);
},
error:function(data){
alert("Error In Connecting");
}
});
}

How To Detect Shake in Phone using Jquery

In this post I want to explain you how to implement phone shake detection using jquery. Using this I had implemented an interesting concept that shake the mobile device and get the product discount. Very easy to use add this to your e-commerce project, sure this user experience feature will attract the people for more sales. Please try these live demos with your mobile device, this works with mobile web browser device accelerometer.

Products Table
Product table contains all the product details. 
CREATE TABLE `products` (
`product_id` int AUTO_INCREMENT,
`product_name` varchar(150),
`product_img` text,
`price` float,
`discount` int,
PRIMARY KEY (`product_id`)
);

JavaScript
Contains JavaScript code, $.shake function detects phone shake and it callback phoneShake().
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.ios-shake.js"></script>
<script type="text/javascript" src="js/jquery.ui.shake.js"></script>
<script type="text/javascript">
$(document).ready(function() {

setInterval(function()
{
$('#shake').shake();
}, 3000);

function phoneShake()
{
var productID=$(".product_id").attr('id');
var url='ajax_discount.php';
var data='product_id='+productID;

$.ajax({
type:"POST",
url:url,
data:data,
dataType:"json",
success:function(data)
{
$('#shake').hide();
$('#result').html(data);
}
});
}

$.shake({
callback: function()
{
phoneShake();
}
});
});
</script>

PHP Code
Contains PHP code,  getting product details from products table. 
<?php
require 'db.php';
$product_id='1';
$sql = "SELECT product_name,product_img,price FROM products WHERE product_id=:product_id";

try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam("product_id", $product_id);
$stmt->execute();
$products = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;

foreach($products  as $row)
{
$product_name=$row->product_name;
$product_img=$row->product_img;
$price=$row->price;
}
}
catch(PDOException $e)
{
echo 'Connection Error';
}
?>

HTML Code
Set the viewport meta tag for mobile view.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
//JavaScript
</head>
<body>
<div id="<?php echo $product_id;?>" class="product_id">
<img src="<?php echo $product_img;?>" /> 
</div>
<div id="shake">Just shake your phone</div>
<div id="result"><?php echo $price;?></div>
</body>
<html>

ajax_discount.php
This will display product discount.
<?php
require 'db.php';
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST")
{
$product_id=$_POST['product_id'];
$sql = "SELECT discount,price FROM products WHERE product_id=:product_id";

try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam("product_id", $product_id);
$stmt->execute();
$discount = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"product_discount": ' . json_encode($discount) . '}';
}
catch(PDOException $e)
{
echo 'Connection Error';
}
}
?>

db.php
You have to modify database configuration details, before trying this enable php_pdoextension in php.ini file.
<?php
function getDB() {
$dbhost="localhost";
$dbuser="username";
$dbpass="password";
$dbname="database";
$dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbConnection;
}
?>

b