Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  158] [ 7]  / answers: 1 / hits: 110576  / 16 Years ago, tue, february 17, 2009, 12:00:00

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.




  • Nicholas


More From » jquery

 Answers
15

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.


[#99962] Tuesday, February 10, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
joep

Total Points: 32
Total Questions: 97
Total Answers: 104

Location: Wales
Member since Thu, Jul 1, 2021
3 Years ago
joep questions
;