My website allows users to comment on books and articles, with a search input to find relevant sources. Using jQuery, I dynamically load new sources from an outside site based on search terms and display them in a list using AJAX. However, Iām facing two issues:
- Currently, the jQuery runs with every new keypress event after the user enters four characters. Is there a more efficient way to wait for the user to stop typing before triggering the jQuery event?
- While the list styling works fine in Chrome and Safari, Firefox does not apply the CSS for the list, even though it is included in the main CSS sheet associated with the page.
Although I use CodeIgniter, most of the sample code provided should be understandable regardless of familiarity with CI. All CSS is currently in one sheet associated with this page.
Here is the initial form HTML:
<?=form_open('/scrawls/add')?>
<h2>Add a Scrawl</h2>
<div id="scrawl-source-container">
<p class="form-par">Search for a reference:</p>
<input type="text" name="scrawl_source_search" id="scrawl-source-search">
<div id="scrawl-source-suggestions">
// suggestions list goes here
</div>
</div>
<input type="hidden" name="scrawl_source_id" value=0 id="scrawl-source-id">
// redacted code for other fields
<div id="selected-ref">
You've selected: <span id="selected-ref-name"></span>
</div>
// redacted code for other fields
<?=form_submit('scrawl_submit','Post')?>
<?=form_close()?>
Here is the JavaScript code (not my strong suit):
$(document).ready(function() {
$("input#scrawl-source-search").keypress(function() {
var length = $(this).val().length;
if (length > 4) {
// add loading functionality here
// make Ajax request to fetch matching sources
$.post("http://mysite.com/refs/refMatch",{ term:$("input#scrawl-source-search").val()}, function(data) {
if (data=="No output") {
$("div#scrawl-source-suggestions").show();
$("div#scrawl-source-suggestions").html("No matches.");
} else {
$("div#scrawl-source-suggestions").html(data).hide();
$("div#scrawl-source-suggestions").slideDown();
}
});
}
});
});
The 'refMatch" page, accessed via AJAX, checks an external site for new additions to the database and outputs matches. Here is the output file:
<?php
if(isset($refs))
{
echo '<ul class="autocomplete-list">';
foreach($refs as $r)
{
echo '<li class="autocomplete-entry">';
echo '<span class="source-id" style="display:none">'.$r->ref_id.'</span><span class="source-title">'.$r->ref_title.'</span>';
if($r->ref_author != '') {
echo ' by <span class="source-author">'.$r->ref_author.'</span>';
}
echo '</li>';
}
echo '</ul>';
} else {
echo "No output";
}
In conclusion, why does Firefox not style the AJAX output correctly, and what is a more efficient way to trigger the jQuery AJAX call?