How to get result from database on the change of values in text box using Ajax?
I am working in PHP and Mysql Combo
I need to search the results from DB and store in a hidden field , on change of the value user inserts in a text bo开发者_JS百科x.
How can I do this Using Ajax?
You will need a few things:
- Your main page.
- A php file which processes the given input (the search string) and outputs only the value you want to store in the hidden field (returnsearchresults.php in the example below).
- Some javascript to make the ajax work.
I'd recommend using jQuery for the ajax though you could always roll your own if you're a masochist.
On your main page you will need something like this:
$("#ID_OF_SEARCH_BOX_GOES_HERE").keydown(function(event) {
search_string = $("#ID_OF_SEARCH_BOX_GOES_HERE").val();
$("#ID_OF_HIDDEN_FIELD_GOES_HERE").load("returnsearchresults.php?q="+search_string);
});
Edit: Here's an idea of what returnsearchresults.php should look like:
<?php
$search_string = $_GET['q'];
// ADD SOME CHECKS IN HERE TO PREVENT SQL INJECTION OR WHATEVER
$SQL = "SELECT
whatever_you_need,
FROM
your_database
WHERE
the_column
LIKE
'%$q%'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo $row[0], ', '; // obviously this line depends on how
// you need to format your hidden field.
}
?>
Note: I haven't included code to open/close the database connection or to verify that $_GET['q'] isn't malicious. I'll leave that up to you!
精彩评论