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
?>

No comments:

Post a Comment