Re: Regarding Ajax in PHP

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



try xajax. its best, *xajax*project.org


On Tue, Aug 26, 2008 at 1:41 PM, Brian Etheridge <
Brian.Etheridge@xxxxxxxxxxx> wrote:

> Hi Vijaya,
> Have a look at prototype.js at http://www.prototypejs.org/ which has
> excellent support for Ajax.
>
> Here's an example.  The code below comes from two files.  The first is
> the HTML and the second is a php file (which could be converted to a
> class).    All you need to do is download the prototype javascript
> library and put it in your directory system, thus:
> /prototype/js/prototype.js.  Read the prototype documentation and all
> will be clear, hopefully.
>
> Have a look at JSON - you could start here:
> http://en.wikipedia.org/wiki/JSON
>
> =======================
> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
> <HTML>
>  <HEAD>
>  <title>AjaxExample</title>
>  <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
>  <META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
>  <META HTTP-EQUIV="EXPIRES" CONTENT="-1">
>  <script src="/prototype/js/prototype.js"
> type="text/javascript"></script>
>  <style>
>
> a { color:#442b62; text-decoration:underline; }
> a:link { color:#442b62; text-decoration:underline;}
> a:visited { color:#442b62; text-decoration:underline;}
> a:hover { color:#8e57d0;}
> a:active { color:#8e57d0; }
>
> body{
>  text-align:left;
>  font-size:100.01%;
>  font-family:Arial, helvetica, sans-serif;
>  color:#a4a4a4;
>  background-color:#fff;
>  margin:20px;
>  padding:0;
> }
> h1 {
>  font-weight:bold;
>  font-size:24px;
> }
> img{
>  border:none;
> }
> .title {
>  font-weight:bold;
>  font-size:16px;
> }
> .text {
>  font-weight:bold;
>  font-size:12px;
> }
> .link {
>  font-weight:bold;
>  font-size:12px;
> }
> #content {
>  color:#c40000;
> }
> #monitor {
>  color:#0000c4;
> }
>  </style>
>  </HEAD>
>  <body>
>  <form name="userForm" id="userForm" method="get">
>   <table border="0" cellpadding="4" cellspacing="0">
>    <tr>
>     <td width="100%" colspan="2"><h1>Simple AJAX Name Search
> Example</h1>
>     </td>
>    </tr>
>    <tr>
>     <td class="title" width="100%" colspan="2">See ajaxManager.php for
> details regarding the server side code.</td>
>    </tr>
>    <tr>
>     <td width="100">Name search pattern:</td>
>     <td><input type="text" id="pattern" name="pattern"
> onkeyup="show_data();"></td>
>    </tr>
>    <tr>
>     <td width="100" valign="top">Results:</td>
>     <td>
>      <div id="resultMessage" name="resultMessage"></div>
>     </td>
>    </tr>
>    <tr>
>     <td width="100" valign="top">Matching names:</td>
>     <td>
>      <select name="personList" id="personList"
> style="width:200px;size:0;"><option value="None">None</option></select>
>     </td>
>    </tr>
>   </table>
>  </form>
>  <br /><br />
>  <div class="link"><a
> href="/prototype/index.html">&lt;&lt;Back</a></div>
>
>  <script type="text/javascript">
> <!--//
>  // This is an example of using Ajax.
>
>  function show_data() {
>
>  // Initialise results fields.
>  $('resultMessage').innerHTML = '';
>  clearPersons('Searching...');
>
>  if ($('pattern').value.length <= 0) {
>   clearPersons('None');
>  }
>  else {
>    //Append the name to search for to the requestURL
>    // To ensure IE7 does not ignore the no-cache directive, insert a
> unique value in the url.
>    var now = new Date();
>    var url = 'ajaxManager.php?t='+now.getTime()+'&';
>    // Note use of the prototype '$' function to get the element by id.
>    var params = ('action=GetUserNamesExample' +
>           '&pattern=' + $('pattern').value);
>
>    // Create an Ajax Request object to handle the request.
>    var ajax = new Ajax.Request(
>     url,
>     { method: 'get',
>      parameters: params,
>      onSuccess: reportSuccess,
>      onFailure: reportError,
>      asynchronous: false
>     });
>  }
>  }
>
>  function reportError(request) {
>  alert("An error was detected during processing.  Please contact the
> website administrator.\n" +
>    "Error text: "+request.responseText);
>  }
>
>  function reportSuccess(request) {
>
>  //alert("reportSuccess called with: "+request.responseText);
>
>  // Use the JSON object returned from the server to populate the
> result.
>  var obj = eval(request.responseText);
>  if (obj.status=='ok') {
>   $('resultMessage').innerHTML = obj.message;
>   // Do something with the returned data.
>   loadPersons(request);
>  }
>  else {
>   $('resultMessage').innerHTML = obj.message;
>   alert("An error was detected during processing:\n"+obj.message);
>   clearPersons('None');
>  }
>
>  }
>
>  function loadPersons(request) {
>  // Use the JSON object returned from the server to populate the
> result.
>  var obj = eval(request.responseText);
>  if (obj.status=='ok') {
>   if (obj.dataArray.length>0) {
>    for (var i=0; i<obj.dataArray.length; i++) {
>     var item = eval(obj.dataArray[i]);
>     //alert('id='+item.id+', name='+item.name);
>     // Load the listbox with the result.
>     document.userForm.personList[i]=new Option(item.name, item.id);
>    }
>   }
>   else {
>    alert('No entries were found for the selection criteria.');
>   }
>  }
>  else {
>   alert("An error was detected during processing:\n"+
>    "Error text: "+obj.message);
>  }
>  }
>
>  function clearPersons(optionText) {
>  var len = document.userForm.personList.length;
>  for (var i=0; i<len; i++) {
>   // NB Just keep removing the first element, because the list changes
> dynamically
>   // when removing entries.
>   document.userForm.personList.remove(0);
>  }
>  document.userForm.personList[0]=new Option(optionText, 'null');
>  }
>
> // -->
>  </script>
>  </body>
> </HTML>
>
> =======================
> <?php
>
>  $personDataAry =
> array('Abraham','Arthur','Mickey','Charlie','Freddie','George','Harry','
> Ian',
>
> 'Mary','Betty','Valerie','Zebedie','Horace','Orist','Nathan','Jayden',
>
> 'Dave','Ricky','Nathaniel','Patrick','Peter','Barrie','Jimmy','Bart',
>
> 'Gordon','Roger','Steve','Louise','Kim','Ben','Russ','Maggie');
>  sort($personDataAry);
>
>  $jsonVar = "fiddle";
>  // Handle Ajax action request.
>  $action = $_REQUEST["action"];
>  switch($action) {
>  case "GetUserNamesExample":
>   $jsonVar = handleGetUserNamesExample($_REQUEST["pattern"]);
>   break;
>  // Put your customer request action processing here.
>  // ...
>  default:
>   // Unknown request action.
>   $jsonVar = ("result={ "
>    +" status:'error'"
>    +",message:'Unknown action "+$action+"'"
>    +"};");
>   break;
>  }
>  print($jsonVar);
>  exit();
>
>
>  /// <summary>
>  /// Example method for handling the GetUserNamesExample action.
>  /// </summary>
>  function handleGetUserNamesExample($p_pattern) {
>  global $personDataAry;
>
>  // Set up variables we will be returning to the caller, via a JSON
> object.
>  $personAry = array();
>  $status = "ok";
>  // Do our various processing to determine the state of the returned
> vars.
>  // This would normally be a db lookup.  Hard coded here for
> illustration only.
>  $atLeastOne = false;
>  for($i=0; $i<count($personDataAry); $i++) {
>
>   $pos = stripos($personDataAry[$i], strToLower($p_pattern));
>   if ($pos===false) {
>    // Did not find any hits.
>   }
>   else if($pos>=0) {
>
>    $atLeastOne = true;
>
>    $person = new Person();
>    $person->id = "ID".$i;
>    $person->name = $personDataAry[$i];
>    $personAry[] = $person;
>   }
>  }
>  if ($atLeastOne) {
>   $message = 'Returned '.count($personAry).' elements';
>  } else {
>    $status = "error";
>    $message = "Try another search pattern";
>  }
>  // Build the JSON object we are going to return to the caller.
>  return convertArrayToJson($status, $message, $personAry);
>  }
>
>  /// <summary>
>  /// Iterate through the array of return person and convert to a JSON
> parameter.
>  /// </summary>
>  function convertArrayToJson($p_status, $p_message, $p_array) {
>
>  // Build the JSON object we are going to return to the caller.
>  // Also include the status of the processing, the returned data and
> any messages.
>  $jsonVar = ("result={ "
>   ." 'status':'".$p_status."'"
>   .",'message':'".$p_message."'"
>   .",'dataArray':[");
>
>   if (isset($p_array) && is_array($p_array) && count($p_array)>0) {
>    $comma = "";
>    foreach($p_array as $obj) {
>     if(!empty($obj)) {
>      // Add JSON array element for each object.
>      $jsonVar .= ($comma.$obj->getAsJsonObject());
>      $comma = ",";
>     }
>    }
>   }
>   $jsonVar .= ("]"."};");
>  // Return the result.
>  return $jsonVar;
>  }
>
>  class Person
>  {
>  var $id;
>  var $name;
>
>  function getAsJsonObject() {
>   return("{'id':'".$this->id."'".",'name':'".$this->name."'"."}");
>  }
>  }
>
> ?>
>
> =======================
>
> That should help.
> Brian
>
>
> [Non-text portions of this message have been removed]
>
>
> ------------------------------------
>
> Are you looking for a PHP job? Join the PHP Professionals directory Now!
> http://www.phpclasses.org/professionals/Yahoo! Groups Links
>
>
>
>


-- 
A.M.Doctor


[Non-text portions of this message have been removed]


[Index of Archives]     [PHP Home]     [PHP Users]     [PHP Soap]     [Kernel Newbies]     [Yosemite]     [Yosemite Campsites]

  Powered by Linux