Sunday, May 17, 2015

Standard JQuery AJAX Code

 

Further to my code which teaches you how to retrieve JSON data from the server, here is another example which shows you how to post JSON data to the server and store it in a mySQL database.

There are three basic steps

  1. Link to AJAX code
  2. Write the JavaScript code to call the server side file
  3. Write the server side code  that will be called by the JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>



function handleSaveLocation(){
$(
"#message").html("Storing the location to server..");
var fileurl = "http://www.yourwebsite.com/saveLocation.php";
var parameterurl_1 = "latitude=" + $("#txtlatitude").val();
var parameterurl_2 = "longitude=" + $("#txtlongitude").val();
var url = fileurl + "?" + parameterurl_1 + "&" + parameterurl_2;
$.post(url, saveLocationToServer);
}
//end function

function saveLocationToServer(data,status){
var obj = JSON.parse(data);
var s = obj[0];

$(
"#message").html("Location stored in server under record id: #" + s);

}
//end saveLocationToServer(data,status)


<?
$latitude
= $_REQUEST["latitude"];
$longitude
= $_REQUEST["longitude"];

try {

$mysqli
= new mysqli('localhost','username','password','database');
$query
= "INSERT INTO locations (latitude,longitude) VALUES (?,?)";

if ($stmt = $mysqli->prepare($query)) {
$stmt
->bind_param('dd', $latitude,$longitude);
$stmt
->execute();
$insert_id
= $mysqli->insert_id;
$data
= array();
$datarow
= array($insert_id);
array_push($data, $datarow);
echo json_encode($data);
mysqli_stmt_free_result($stmt);
$stmt
->close();
}
//end if $stmt = $mysqli->prepare($query))
} //end try
catch (Exception $exception){
echo $exception;
}
//end catch
?>

Monday, February 16, 2015

Standard JQuery AJAX Code


First, ensure you have linked ot the JQuery AJAX Javascript source files.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


Add in event handlers for the UI form elements that will invoke the AJAX query upon interaction.

$("#btnGetCustomerRecord").click(handleGetCustomerRecordButtonClick);


function getCustomerRecordFromServer(data,status){
       var obj = JSON.parse(data);
      
       var s1 = "<b>Customer Name</b>:" + obj[0][0] + "<br/>";
       var s2 = "<b>Customer Address</b>:" + obj[0][1] + "<br/>";
      
      $("#divCustomerRecord").html(s);
      
} //end getCustomerRecordFromServer

function handleGetCustomerRecordButtonClick(){
       ////alert("Handle Button Click");
       var fileurl = "http://viewcustomer.php";
       var parameterurl = "customerid=" + $("#txtcustomerid").val();
       var url = fileurl + "?" + parameterurl;
       ////alert(url);
      $.get(url, getCustomerRecordFromServer);
} //end function


On the server side, here’s the PHP code that returns the data

<?
  $customerid = $_REQUEST["customerid"];
  
  try {
  
    $mysqli = new mysqli('localhost','userid','password','database');
    $query = "SELECT CustomerName, CustomerAddress FROM Customers WHERE customerid=?";
      
    if ($stmt = $mysqli->prepare($query)) {
        $stmt->bind_param('d', $customerid);
        $stmt->execute();
        $stmt->bind_result($r1, $r2);    
        
        $data = array();
        while (mysqli_stmt_fetch($stmt)) {
            $datarow = array($r1,$r2);
            array_push($data, $datarow);
        } //end while
        
        echo json_encode($data);
        mysqli_stmt_free_result($stmt);
        $stmt->close();
      } //end if $stmt = $mysqli->prepare($query))
  } //end try
  catch (Exception $exception){
      echo $exception;
  } //end catch
?>

Thursday, February 12, 2015

Basic Skeleton for using the Facebook PHP SDK v.4.4.0

 

<? session_start();

require_once( 'Facebook/FacebookSession.php' );
require_once( 'Facebook/FacebookRedirectLoginHelper.php' );
require_once( 'Facebook/FacebookRequest.php' );
require_once( 'Facebook/FacebookResponse.php' );
require_once( 'Facebook/FacebookSDKException.php' );
require_once( 'Facebook/FacebookRequestException.php' );
require_once( 'Facebook/FacebookAuthorizationException.php' );
require_once( 'Facebook/GraphObject.php' );

use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;

// init app with app id (APPID) and secret (SECRET)
$appID = 'YOUR_APP_ID';
$appSecret = 'YOUR_APP_SECRET';
$appLoginURL = 'https://YOUR_APP_LOGIN_URL';
$appLogoutURL = 'https://YOUR_APP_LOGOUT_URL';

FacebookSession
::setDefaultApplication($appID, $appSecret);

$helper = new FacebookRedirectLoginHelper($appLoginURL ); // login helper with redirect_uri

try
{
$session = $helper->getSessionFromRedirect();
}
catch( FacebookRequestException $ex )
{
// When Facebook returns an error
}
catch( Exception $ex )
{
// When validation fails or other local issues
}


if ( isset( $session ) ) // see if we have a session
{
$request = new FacebookRequest( $session, 'GET', '/me' ); // graph api request for user data
$response = $request->execute();

$graphObject = $response->getGraphObject(); // get response
$graphObject_keys = array("id", "email", "first_name", "last_name", "gender", "link", "locale", "name", "timezone", "updated_time", "verified");
for ($i=0; $i<count($graphObject_keys); $i++){
echo $graphObject_keys[$i] . " : " . $graphObject->getProperty($graphObject_keys[$i]) . "<br/>";
}

$logoutURL = $appLogoutURL . '">Logout</a>';
echo '<a href="' . $helper->getLogoutUrl( $session, $logoutURL);
}
//end if
else
{
echo '<a href="' . $helper->getLoginUrl() . '">Login</a>'; // show login url
} //end else

?>

Sunday, August 3, 2014

mysqli Prepared statements using the SELECT syntax

 

$mysqli = new mysqli('localhost','username','password','databasename');
$query
= "SELECT id,name FROM customers WHERE id=?";

if ($stmt = $mysqli->prepare($query)) {
$stmt
->bind_param('s', $_id);
$stmt
->execute(); /* execute query */
$stmt
->store_result(); /* Store the result to get properties */
$num_of_rows
= $stmt->num_rows; /* Get the number of rows */
$stmt
->bind_result($id,$name); /* Bind the result to variables */
while ($stmt->fetch()) {
printf(
"%s %s", $id, $name);
}
$stmt
->close();
$mysqli
->close();
}
//end if