顯示具有 Ajax 標籤的文章。 顯示所有文章
顯示具有 Ajax 標籤的文章。 顯示所有文章

2012年4月4日 星期三

Ajax Poll 投票範例

這是一個 AJAX Poll 投票的範例

1. HTML Code(ajax_poll.htm):

<html>
  <head>
    <meta charset="utf-8" />
    <title>AJAX Poll</title>
    <script src="ajax_poll.js"></script> 
  </head>
  <body>
    <h3><a href="http://www.w3schools.com/php/php_ajax_poll.asp">AJAX Poll</a></h3>
    <div id="poll">
      <h2>Do you like PHP and AJAX so far?</h2>
      <form>
        Yes: <input type="radio" name="vote" value="0" onclick="getVote(this.value)"><br />
        No: <input type="radio" name="vote" value="1" onclick="getVote(this.value)">
      </form>
    </div>
    <a href="index.htm">Home</a>
  </body>
</html>



2. Javascript Code(ajax_poll.js):

var xmlHttp;

function getVote(int) {
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null) {
    alert("Browser does not support HTTP Request");
    return;
  }
  var url="ajax_poll.php";
  url=url+"?vote="+int;
  url=url+"&sid="+Math.random();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function stateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
    document.getElementById("poll").innerHTML=xmlHttp.responseText;
  }
}

function GetXmlHttpObject() {
  var objXMLHttp=null;
  if (window.XMLHttpRequest) {
    objXMLHttp=new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return objXMLHttp;
}



3. PHP Code(ajax_poll.php):

<?php

$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "ajax_poll.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) $yes = $yes + 1;
if ($vote == 1) $no = $no + 1;

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);

?>

<h2>Result:</h2>
<table>
  <tr>
    <td>Yes:</td>
    <td>
      <img src="images\\poll.gif" width='<?php echo(100*round($yes/($no+$yes),2)); ?>' height='20'>
      <?php echo(100*round($yes/($no+$yes),2)); ?>%
    </td>
  </tr>
  <tr>
    <td>No:</td>
    <td>
      <img src="images\\poll.gif" width='<?php echo(100*round($no/($no+$yes),2)); ?>' height='20'>
      <?php echo(100*round($no/($no+$yes),2)); ?>%
    </td>
  </tr>
</table>



4. TXT Code(ajax_poll.txt):

0||0



5. 下載 poll.gif 檔案, 放到 images 資料夾下.


6. 寫好後, 執行 ajax_poll.htm, 完成!

2012年4月3日 星期二

Ajax Login 登入範例

這是一個 AJAX Login 登入的範例

1. HTML Code(user_login.htm):

<html>
  <head>
    <meta charset="utf-8"/>
    <title>AJAX Login</title>
    <script src="user_login.js"></script>
  </head>
  <body>
    <h3><a href="http://www.aleixcortadellas.com/main/2009/03/01/ajax-post/">AJAX Login</a></h3>
    <form name="myform" id="myform">
      <div id="msg" style="color:red;display:none;"></div>
      Account: <input type="text" name="account"><br/>
      Password: <input type="password" name="pwd"><br/>
      <span id="btn"><input type="button" name="sb" id="sb" value="Login"></span><br/>
      <span style="color:blue;">(tip: guest / guest)</span><br/>
      <a href="index.htm">Home</a>
    </form>
  </body>
</html>



2. Javascript Code(user_login.js):

window.onload = initPage;
function initPage() {
  // 取得「送出」按鈕的參考
  var subBtn = document.getElementById("sb");
  // 為按鈕加入事件處理器
  subBtn.onclick = function () {
    MakeRequest(); // 建立請求的函式
  }
}

function createRequest() {
  if (window.XMLHttpRequest) {
    return new XMLHttpRequest();
  } else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
  }
}

var request = createRequest(); // 建立請求物件

function MakeRequest() {
  form = document.getElementById("myform");
  if (request != null) {
    // 取得輸入的文字
    var sPost = "";
    for(i=0;i<form.elements.length;i++) {
      inp = form.elements[i];
      switch(inp.type) {
        case "text":
        case "textarea":
        case "select-one":
        case "radio":
        case "password":
          if (inp.name && inp.value) {
            sPost+="&"+escape(inp.name)+"="+escape(inp.value);
          }
          break;
        default:
          break;
      }
    }

    var url = "user_login.php?1=1";

    // 利用 POST 方法、請求目的地 url、true 為非同步
    request.open("POST", url, true);

    // 回應處理函式 displayResult
    request.onreadystatechange = displayResult;
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.send(sPost); // 送出請求
  }
}

function displayResult() {
  if (request.readyState == 4) { // 確認 readState
    if (request.status == 200) { // 確認 status
      var disp = document.getElementById("msg"); // 取得顯示位置
      disp.innerHTML = request.responseText;
      if (request.responseText=="Succcess") {
        var btnInput = document.getElementById("btn"); // 取得按鈕位置
        btnInput.style.display="none";
      }
      disp.style.display="block";
    }
  }
}



3. PHP Code(user_login.php):

<?php

$aRow =&$_POST;
$aStr = array();

if (!isset($aRow['account'])) $aRow['account']="";
if (!isset($aRow['pwd'])) $aRow['pwd']="";

if (!$aRow['account']) $aStr[] = "Enter account";
if (!$aRow['pwd']) $aStr[] = "Enter password";

if (!count($aStr)) {
  if ($aRow['account']=="guest" and $aRow['pwd']=="guest") {
    $aStr[] = "Succcess";
  } else {
    $aStr[] = "Account and password is not correct";
  }
}
echo implode("<br>",$aStr);

?>



4. 寫好後, 執行 user_login.htm , 完成!

Ajax Suggest 建議的範例

Ajax Suggest 建議的範例:

1. HTML Code(clienthint.htm):
<html>
  <head>
    <script src="clienthint.js"></script>
  </head>
  <body>
    <h3><a href="http://www.w3school.com.cn/php/php_ajax_suggest.asp">Ajax Suggest</a></h3>
    <form>
      First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
    </form>
    <p>Suggestions: <span id="txtHint" /></p>
    <a href="index.htm">Home</a>
  </body>
</html>


2. Javascript Code(clienthint.js):
var xmlHttp;
function showHint(str) {
  if (str.length==0) {
    document.getElementById("txtHint").innerHTML="";
    return;
  }
  xmlHttp=GetXmlHttpObject()
  if (xmlHttp==null) {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url="clienthint.php";
  url=url+"?q="+str;
  url=url+"&sid="+Math.random();
  xmlHttp.onreadystatechange=stateChanged;
  xmlHttp.open("GET",url,true);
  xmlHttp.send(null);
}

function stateChanged() {
  if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
    document.getElementById("txtHint").innerHTML=xmlHttp.responseText
  }
}

function GetXmlHttpObject() {
  var xmlHttp=null;
  try {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return xmlHttp;
}


3. PHP Code(clienthint.php):
<?php

// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Eric";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0) {
  $hint="";
  for($i=0; $i<count($a); $i++) {
    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) {
      if ($hint=="") {
        $hint=$a[$i];
      } else {
        $hint=$hint." , ".$a[$i];
      }
    }
  }
}

//Set output to "no suggestion" if no hint were found
//or to the correct values
if ($hint == "") {
  $response="no suggestion";
} else {
  $response=$hint;
}

//output the response
echo $response;
?>


4. 寫好後, 執行 clienthint.htm , 完成!