rrfive
rrfive

Reputation: 165

Ajax Form Submit with submit button

I've got form which when submitted (using AJAX) returns a bunch of client details. The form field collects the user's ID, submits and returns the results. I'd like to use a submit button rather than an onchange on the textbox but am unable to submit the textbox value and have the anything returned.

This seems like it should be simple but I'm again in need of some help.

Thanks, @rrfive

Form:

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

Upvotes: 2

Views: 5602

Answers (2)

Killswitch
Killswitch

Reputation: 346

<form onsubmit="return false;">

Upvotes: 0

Matt Healy
Matt Healy

Reputation: 18531

You don't need to pass in the whole form, just the "user" input.

Form:

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

In your PHP, please remember you need to sanitise the input before using it in a database query. Read up on mysql_real_escape_string or prepared statements

Upvotes: 2

Related Questions