I know how to do this with pure PHP but I need to do this without reloading the page. Is there anyway with jQuery to effectively pull back some database results (based on what a user has input in the first text field on a form) then populate some of the remaining fields with data pulled back from a db query?
Essentially I would like to see the user move away from the text field (either by tabbing out or by click in the next field) and boom, the query is submitted using the value entered in that field and the subsequent fields are then populated w/o a page reload.
I am familiar with the basics of jQuery but I haven't used it to do anything like this in which I am pulling data back from the server and trying to populate it client side.
Any suggestions / examples on how to best get started with this would be very much appreciated. Thanks.
Assuming this example HTML:
<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />
You could have this javascript:
$("#email").bind("change", function(e){
$.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
function(data){
$.each(data, function(i,item){
if (item.field == "first_name") {
$("#first_name").val(item.value);
} else if (item.field == "last_name") {
$("#last_name").val(item.value);
}
});
});
});
Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:
<?php
//look up the record based on email and get the firstname and lastname
...
//build the JSON array for return
$json = array(array('field' => 'first_name',
'value' => $firstName),
array('field' => 'last_name',
'value' => $last_name));
echo json_encode($json );
?>
You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.
Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With