2012-01-15 333 views
2

我有表單,提交時(使用AJAX)返回一堆客戶端詳細信息。表單字段收集用戶的ID,提交併返回結果。我想使用提交按鈕而不是文本框上的onchange,但無法提交文本框的值並返回任何內容。Ajax表單提交併提交按鈕

這看起來應該很簡單,但我再次需要一些幫助。

感謝, @rrfive

形式:

<form> 
<strong>Client ID:</strong> 
<input name="user" type="text" class="textBox" maxlength="10" /> 
<input type="submit" onclick="showUser(this.form); return false;"> 
</form> 

JS:

<script type="text/javascript"> 
function showUser(str) 
{ 
if (str=="") { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
if (window.XMLHttpRequest) { 
    xmlhttp=new XMLHttpRequest(); 
    } 
else { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","includes/fetchUser.php?userID="+str,true); 
xmlhttp.send(); 
} 
</script> 

PHP:

<?php 
define('INCLUDE_CHECK',true); 
include 'config.php'; 

$userID=$_GET["userID"]; 
$sql="SELECT * FROM users WHERE ID = '".$userID."'"; 
$result = mysql_query($sql); 

$returned_rows = mysql_num_rows ($result); 

    if ($returned_rows == 0){ 
     echo '-- No results found --'; 
    } 
    else { 
     while($row = mysql_fetch_array($result)) { 
     echo "<div class='column'>"; 
     echo '<label>Name:</label>' . $row['lastName'] . ' 
     echo '</div>'; 
     } 
    } 

mysql_close($con); 
?> 

回答

2

你並不需要在整個傳遞形式,只是「用戶「輸入。

形式:

<form name="myform"> 
<strong>Client ID:</strong> 
<input name="user" type="text" class="textBox" maxlength="10" /> 
<input type="submit" onclick="showUser(document.myform.user.value); return false;"> 
</form> 

在你的PHP,請記住,你需要在數據庫中查詢使用前淨化輸入。請閱讀mysql_real_escape_stringprepared statements

0
<form onsubmit="return false;"> 
+0

它會阻止表單提交。現在,您可以順利地進行ajax呼叫... – Killswitch 2012-01-15 11:50:59