I have a Ajax PHP MySQL live search that basically pulls out food items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular result item, and for that to open up, just below the item clicked, a box with a few radio buttons listing options with various amounts of that particular food item. The user would then be able to select an amount option and click submit to save their selection.
I know PHP and MySQL and HTML quite well, but JS is a bit of a challenge, so I'd appreciate if you could be detailed in your answer.
Below are some code snippets with what I have at this point:
The HTML search form:
<input type="text" size="30" name="food_name" id="q" value="" onkeyup="sendRequest(this.value);" autocomplete="off"/>
The AJAX code on same page w/ search form:
function createRequestObject() {
var req;
if(window.XMLHttpRequest){
// Firefox, Safari, Opera...
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
// Internet Explorer 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Problem creating the XMLHttpRequest object');
}
return req;
}
// Make the XMLHttpRequest object
var http = createRequestObject();
function sendRequest(q) {
// Open PHP script for requests
http.open('get', 'checkfoods.php?q='+q);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4 && http.status == 200){
// Text returned FROM the PHP script
var response = http.responseText;
if(response) {
// UPDATE ajaxTest content
document.getElementById("searchResults").innerHTML = response;
}
}
}
The PHP script that looks into a table called FOOD_DES into MySQL and brings back the results populating the drop-down list of foods:
include 'my-food-dtabase.php';
$searchQry = isset($_GET['q']) ? mysql_real_escape_string($_GET['q']) : false;
if ($searchQry) {
$searchString = $_GET['q'];
$sql = mysql_query("SELECT NDB_No, FdGrp_Cd, Long_Desc FROM FOOD_DES WHERE Long_Desc LIKE '%".$_GET['q']."%' ORDER BY Long_Desc ASC");
if($searchString != NULL) {
while($row = mysql_fetch_assoc($sql)) {
echo "<span id=foodlist>".$row['Long_Desc']."<br /></span>";
}
}
if(mysql_num_rows($sql) == 0) {
echo "<span class=medium_white>Food item not found. Try a different name or keyword.</span>";
}
}
This isn't necessarily a complete answer but a pointer in the right direction.
You will save yourself a tonne of time and effort by using jQuery over pure JavaScript. It will also reduce your step 2 down to a few lines of code as it comes with its own Ajax API. Here's a tutorial on its Ajax system - much easier!
jQuery UI is a great extension to jQuery which helps you to build user interfaces, part of this is the dialog widget. I think the 'Modal form' dialog example is very similar to what you are trying to achieve when you click the 'create new user' button. Click 'View Source' to see how they did it.
Also from what I can see in step 3 you aren't sanitising your query, $_GET['q'] is being thrown right into your query string. You should replace this with $searchQry which you already defined a few lines above.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
});
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Description
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
http://koding.info/2013/07/ajax-search-box-php-mysql-jquery/
I have implemented a demo Live search application which uses Wordpress database.
Take a look.
it may help you.
Related
This is my current plan:
Clicking on a row selects or gets the id of the row, then this id is passed to a delete script most likely via AJAX or an HTTP request. The problem I have is how to identify the row from the click using "this" this as in show below:
$( this ) {
// get id and send to delete script
}
I have echoed out the rows so that I have the id row
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'dbconnect.php');
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT COUNT(*) FROM entries";
if ($result = $link->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
if($row[0]==0){
echo "There are no entries.";
}else {
$query2 = "SELECT id,saying,date,thumbs_up,comments FROM entries ORDER by ID ASC ";
if (($result = $link->query($query2))) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo
'<div class="container" align="center"">'.
'<div class="entry-container" align="left">'.
$row[1]." ".
'</div>'.
'<div class="x" align="center">'.
'<button class="red" name="remove" onclick="remove_entry();">remove entry'.
' '.
$row[0].
'</button>'.
'</div>'.
'</div>'.
'<br>'
;
}
}
}
}
/* free result set */
$result->close();
}
?>
remove_entry(); doesn't do anything yet, presumably it will send the id to the delete script which then removes the row using the DELETE command
<script type="text/javascript">
function remove_entry() {
var answer = confirm("Delete this entry?")
if (answer){
//some code
}
else{
//some code
}
}
</script>
What is the most direct and effective / efficient way to do this?
I would even prefer not to show id, just use a simple x for the delete button, I echoed the id so that I had it to use to identify the row to be deleted.
Using jQuery can do :
HTML
<div class="entry-container" align="left" id="'.$row[0].'">
JS
$(function(){
$('button.red').click(function(){
var $row = $(this).closest('.entry-container'),
rowId = $row.attr('id');
$.post('/path/to/server', {id: rowId}, function(resp){
if(resp =='ok'){
$row.slideUp(function(){ $row.remove() });
}
});
});
});
Then remove your inline onclick
In PHP receive the id with $_POST['id'] and validate it before passing to db query
For starters, don't use 2 SQL queries. Just do the one you use to get data and, if it has no rows, give a different output.
Use semantic markup like so:
'<button type="button" class="remover" id="entry-' . $row[0] . '">remove this entry</button>'
Then in your jQuery, use something like this:
$(function() {
$('.entries').on('click', '.remover', function() {
var eId = this.id.replace(/^\D+/, '');//since IDs should not start with a number
$.post(
'/your/delete/endpoint/',
{
id: eId
},
function(data) {
if (data.ok) {//sending JSON responses are easier to debug and you can add to them later without breaking things
//remove row
}
else {
//display error message
}
}
);
});
});
The second parameter to on() makes it a delegated event, which means you can add new items to an existing set, with the same remover markup, and the new remove buttons will also work.
I have an autocomplete jQuery menu, that output the name of all the users I have, from a MySQL database. I'm trying to link each selection to the proper profile. For that, the URL is something like: /profile.php?id=341, 341 that stands for the ID of the user selected.
The only problem, is that when I try to put the ID of a given user, ALL the ID of ALL the user are shown in the URL... and I want only the ID of the selected user!
I have tried with PHP, but I don't know what to add to the following line to make it work.
$req = mysql_query("select id, Username, EmailAddress from ***");
Should it be something like WHERE Username='username'....? Finally, I know that I should maybe try something else, without PHP, but I just want to test it that way! Thanks!
<input type="text" name="course" id="course" />
<script type="text/javascript" src="jquery.js"></script>
<script type='text/javascript' src='jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#course").autocomplete("/test/test2.php", {
selectFirst: false,
formatItem: function(data, i, n, value) {
//make the suggestion look nice
return "<font color='#3399CC'>" + value.split("::")[0] + "</font>";
},
formatResult: function(data,value) {
//only show the suggestions and not the URLs in the list
return value.split("::")[0];
}
}).result(function(event, data, formatted) {
//redirect to the URL in the string
var pieces = formatted.split("::");
window.location.href = '/profile.php?id='+
<?php
mysql_connect ("***", "***","***") or die (mysql_error());
mysql_select_db ("***");
$req = mysql_query("select id, Username, EmailAddress from ***");
while($dnn = mysql_fetch_array($req))
{
echo $dnn['id'];
}
?>
;
console.log(data);
console.log(formatted);
});
});
</script>
Your MySQL query is true to every user in the database, so it returns all the users. If you want to go to "foo"'s profile, you need to tell the database to fetch "foo"'s id only. A unique row that the user has maybe there email and must be their username.
I assume you have an array in javascript which contains selected users:
var users = new Array("Daniel","Amy","Sandy");
then you need to use ajax to communicate to php:
<script>
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}//This can become an external file to link
</script>
so then you can post data to php:
<script>
var returnedStr = "";
function searchuser(){ //use searchuser function on a button to call
var usersStr = users.toString(); //the string that contain the users separated by ","
var ajax = ajaxObj("POST", "thisurl.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "fail"){ //i didn't include this in php, but you can add it yourself if you can't fetch from mysql
echo "Failed";
} else {
returnedStr = ajax.responseText;// when php echos
}
}
}
ajax.send("u="+usersStr);
}
</script>
then your php will need to handle the string:
<?php
if(isset($_POST["u"])){
$returnArr = array();
$returnStr = "";
$processedArr = explode(',', $_POST['u']); //Here the posted data will turn into an array
$lengthArr = count($processedArr);
for ($i=0; $i<=$lengthArr; $i++)
{
$req = mysql_query("SELECT id FROM xxx WHERE Username='$processedArr[$i]' LIMIT 1");
while($dnn = mysql_fetch_array($req))
{
array_push($returnArr, $dnn['id']);
}
}
$returnStr = implode(",",$returnArr);
echo ($returnStr);
}
?>
Now in Javascript returnedStr will hopefully be 1,2,3 or something like that.
Please comment if this doesn't work!
I'm currently doing a live search form based on Jquery/ajax/php, but it dosent seems to work.
Can you guys se a problem in my code? :)
function getStates(value) {
$.post("search.php",{ partialState: value }, function(data) {
$("#results").html(data);
});
}
<input type="text" onkeyup="getStates(this.value)" />
<div id="results"></div>
Search.php:
$partialStates = $_POST['partialState'];
$states = mysql_query("SELECT institution_name FROM sb_institutions WHERE institution_name LIKE '%$partialStates%'");
while($stateArray = mysql_fetch_array($states)) {
echo "<div>" . $state['institution_name'] . "</div>";
}
Thanks! :)
Your Code looks ok.
The best way to troubleshoot ajax is to use Firefox with Firebug extension.
That way you can see :
if the function is being fired
if the $_POST values are good : url + parameters
what the server sends as a response
if you have errors in your js
All this will be in the console tab of firebug.
after installing firebug right click on the page and choose debug with firebug.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
Please also see this http://crewow.com/AutoSuggest_Search_Tutorial.php
Live Search Tutorial is a PHP Ajax Based Tutorial which containts following pages and Folders.
I have the following ajax.js, which I must use:
var xmlRequest = null;
function ajax(url, parametersArray, callbackFunction, fcnVars) {
if (xmlRequest != null) {
if (xmlRequest.readyState == 2 || xmlRequest.readyState == 3) {
xmlRequest.abort();
xmlRequest = null;
}
}
if (parametersArray == null)
parameters = "";
else
parameters = formatParameters(parametersArray);
if (window.XMLHttpRequest)
xmlRequest = new XMLHttpRequest();
else
xmlRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlRequest.open("POST", url, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
if (xmlRequest.responseText) {
callbackFunction(xmlRequest.responseText, fcnVars);
}
}
}
xmlRequest.setRequestHeader("Content-length", parameters.length);
xmlRequest.setRequestHeader("Connection", "close");
xmlRequest.send(parameters);
}
function formatParameters(parameters) {
var i = 0;
var param = "";
for (index in parameters) {
if (i==0) {
param += index+"="+urlencode(parameters[index]);
} else {
param += "&"+index+"="+urlencode(parameters[index]);
}
i++;
}
return param;
}
function urlencode(clearString) {
clearString = encodeURI(clearString);
clearString = clearString.replace('&', '%26');
return clearString;
}
and I have the following mysql table:
CREATE TABLE `dictionary` (
`word` varchar(64) NOT NULL,
PRIMARY KEY (`word`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
on the end, here is my search page:
<div id = "search">
<form id="searchform" method="post">
Search for Word:
</select>
<input type="text" id="search_term" name="search_term" />
<input type="submit" id="cmdSearch" value="Search" />
</form>
<div id="search_results"></div>
</div>
Now, I have to create a php function which will return an array with the words found in the table, using the above ajax.js
Results should be shown within the search_results div using ajax.
Of course, I will need a javascript code as well.
Anyone can help me to start to build this? I have done similar things with jquery,but now I must use this script, and I have no other way to do it.
Goal is to display the results in the php page without refresh.
Any help will be deeply appreciated
Update:
Here is my php code:
<?php
// add encoding here
header("Content-Type: text/html; charset=iso-8859-7");
// include the database connection here
include 'config.php';
include 'openDb.php';
function findWords(){
// sanitaze the user input
$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysql_escape_string($term);
// query the database. one fileld only, so nothing to optimize here
$sql = "SELECT word FROM dictionary WHERE word like '%$term%'";
$result = mysql_query($sql);
// set the string variable
$string = '';
// if resulta are found then populate the string variable
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
// display the results here in bold and add a new line or break after each result
$string[] = "<b>".$row->user_name."</b><br/>\n";
}
} else {
// if no results are found, inform the visitors...
$string[] = "No matches!";
}
// output the string
return $string[];
Here is the javascript:
<script type='text/javascript'>
ajax("findWord.php", {id:search_term}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:search_term});
</script>
You will have to rely on the ajax function which lets you access whatever it loaded in the callback function:
callbackFunction(xmlRequest.responseText, fcnVars);
And ajax explains how it should be called itself:
ajax(url, parametersArray, callbackFunction, fcnVars)
Even though parametersArray should actually be an object ({index:value, i1:v2,...}) rather than an array ([val1, val2,...]). fcnVars can be an object containing anything that you want passed on to the callback function.
This should work:
ajax("add_page.php", {id:535}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:535});
I have a small problem, I want to a live search that returns me a POST_TITLE and a POST_ID. the title is for the people to see but my main reason is that I want the POST_ID to work with it.
Can someone help me, I posted the code below...
<script>
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your Browser Sucks!\nIt's about time to upgrade don't you think?");
}
}
//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest() {
if (searchReq.readyState == 4 || searchReq.readyState == 0) {
var str = escape(document.getElementById('txtSearch').value);
searchReq.open("GET", '/wp-content/themes/twentyten/livesearch.php?search=' + str, true);
searchReq.onreadystatechange = handleSearchSuggest;
searchReq.send(null);
}
}
//Called when the AJAX response is returned.
function handleSearchSuggest() {
if (searchReq.readyState == 4) {
var sx = document.getElementById('restaurantid')
sx.innerHTML = '';
var ss = document.getElementById('search_suggest')
ss.innerHTML = '';
var str = searchReq.responseText.split("\n");
for(i=0; i < str.length - 1; i++) {
//Build our element string. This is cleaner using the DOM, but
//IE doesn't support dynamically added attributes.
var suggest = '<div onmouseover="javascript:suggestOver(this);" ';
suggest += 'onmouseout="javascript:suggestOut(this);" ';
suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
suggest += 'class="suggest_link">' + str[i] + '</div>';
ss.innerHTML += suggest;
ss
}
}
}
//Mouse over function
function suggestOver(div_value) {
div_value.className = 'suggest_link_over';
}
//Mouse out function
function suggestOut(div_value) {
div_value.className = 'suggest_link';
}
//Click function
function setSearch(value) {
document.getElementById('txtSearch').value = value;
document.getElementById('restaurantid').value = value;
document.getElementById('search_suggest').innerHTML = '';
}
</script>
<form id="frmSearch" action="">
<input type="text" id="restaurantid" name="restaurantid" style="display: none;" />
<input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria" onkeyup="searchSuggest();" autocomplete="off" />
<input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run Search" />
<div id="search_suggest"></div>
</form>
</code>
livesearch.php - THE AJAX PAGE
<code>
<?php
$con = mysql_connect('x', 'x', 'x);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xx", $con);
if (isset($_GET['search']) && $_GET['search'] != '') {
//Add slashes to any quotes to avoid SQL problems.
$search = addslashes($_GET['search']);
//Get every page title for the site.
$suggest_query = mysql_query('SELECT * FROM `mrr_posts` WHERE `post_title` LIKE \'%'.$search.'%\' AND `post_status` LIKE \'publish\' LIMIT 0, 30') or trigger_error("Query: $suggest_query\n<br />MySQL Error: " .mysql_error());
while ($suggest = mysql_fetch_array($suggest_query, MYSQL_ASSOC)) {
//while($suggest = db_fetch_array($suggest_query)) {
//Return each page title seperated by a newline.
echo $suggest['post_title'] . "\n";
}
}
mysql_close($con);
?>
I noticed in the discussion above you're returning JSON now, and parsing it from the client side. And I noticed you tagged your question with jQuery, so I guess you're using that. This isn't an answer to your question, but here are some tips for javascript coding with jQuery that will help simplify your code a ton.
instead of doing your ajax calls using the XMLHttpRequest object directly, just use $.get(url, successFunction)
instead of using getElementById('some-id'), use $('#some-id'), then to do things like empty out the inner html, you can do $('#some-id').html(''). Using the jQuery element instead of HTMLElement, you can also manipulate the DOM in a cross-browser compatible way: http://api.jquery.com/category/manipulation/
instead of building your javascript into your HTML (all those onmouseover and onmouseout handlers), use $('div.suggest_link') to select all divs on the page that have a class of "suggest_link". Then, attach a live event handler which will work on dynamically generated html, like this: $('div.suggest_link').live('mouseover', handleMouseOverForSuggestLink). You can read more about this on jQuery's page: http://api.jquery.com/live/
All these suggestions will work in modern browsers, and will help cut down a lot of code. Good luck!
You should return data from server in JSON (or XML, but JSON is easier), and then parse it in Javascript. Show titles to user, id keep for yourself.
In general xajax might simplify things quite much. Have a look at my answer here:
how to assign a javascript variable to a smarty variable