Your code will look something like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#textfield').blur(function() {
var myId = $(this).val();
if (myId == '') return false;
$.ajax({
type: "POST",
url: "myFile.php",
data: "theID=" +myId,
success: function(fromPHP) {
var allRecd = fromPHP.split('|');
var name = allRecd[0];
var apel = allRecd[1];
$('#textfield2').val(name);
$('#textfield3').val(apel);
}
})
});
}); //END $(document).ready()
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="textfield"></label>
Id:
<input type="text" name="textfield" id="textfield" />
</p>
<p>
<label for="textfield2"></label>
Name:
<input type="text" name="textfield2" id="textfield2" />
</p>
<p>
<label for="textfield3"></label>
Apellido:
<input type="text" name="textfield3" id="textfield3" />
</p>
<p>
<input type="submit" name="button" id="button" value="Enviar" />
</p>
<p> </p>
</form>
</body>
</html>
PHP Side: myFile.php
<?php
$id = $_POST['theID'];
//Do your mysql query here, for example
$result = mysql_query("SELECT * FROM users WHERE user_id = '$id' ");
$n = $result['name'];
$a = $result['apellido'];
$response = $n . "|" . $a;
echo $response;
Notes:
- We use the jQuery
blur()
method to detect when user leaves the text field
- Then get contents of that field (var myId)
- Don't do an AJAX lookup if the field is empty
- Send the assoc var with key name "theID" and contents == myId to file myFile.php, via POST method
- On the PHP side, receive the ID and call it $id (on this side)
- Do you mysql lookup and get the "name" and "apellido" values
- Join them together as a simple string, separated by "|" char
- ECHO them back to the AJAX code block
- IMPORTANT: All data returned from PHP must be handled inside the
success
function!
- Extract the name and apellido values again
- Inject into the correct fields.