Reputation: 331
Once again, I'm stumped. I have a little search field and button to search a mysql db. I want it to append the results in the current page instead of reloading or loading a separate results page.
Here's the script:
<script>
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
//var data = searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
console.log(data);
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
Here's the originating page that is supposed to be appended to, within the ul tags:
<div id="SEARCH2" class="panel">
<div style="margin:20px auto; text-align: center;">
<form method="post" action="do_search.php">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
</ul>
</div>
</div>
And here's the do_search.php that's supposed to insert some html within the ul tags:
<?php
if (isset($_POST['search'])) {
include('db.php');
$word = mysql_real_escape_string($_POST['search']);
$word = htmlentities($word);
$sql = "SELECT id, last_name, first_name, u_name, skype_id, primary_location, phone, status FROM users WHERE (last_name LIKE '%" . $word . "%' OR
first_name LIKE '%" . $word . "%' OR u_name LIKE '%" . $word . "%' OR skype_id LIKE '%" . $word . "%' OR phone LIKE '%" . $word . "%') ORDER BY last_name";
$fetched = mysql_query($sql)or die('query error'.mysql_error());
$end_result = '';
if($fetched){
while($row = MySQL_fetch_array($fetched)):
//TEST TO SEE IF THIS WORKS
$result = $row['id'];
// we will use this to bold the search word in result
$bold = '<span class="found">' . $word . '</span>';
$end_result .= '<li>' . str_ireplace($word, $bold, $result) . '</li>';
endwhile;
echo $end_result;
}
else{
echo '<li>No results found</li>';
}
}
//echo 'crap2';
?>
Upvotes: 0
Views: 3411
Reputation: 9299
Remove the console.log(data);
from your AJAX call. And if you're constantly appending, remove the $("#results").html('');
from beforeSend:
$.ajax({
type: "POST",
url: "do_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
Upvotes: 1