I have a search input and a hidden div. When you start typing in the search input, the hidden div becomes visible and results are brought in. In this case, I'm searching for client names.
开发者_如何学编程It all works fine, however I think my code could be better but I'm not sure exactly where to begin. Each keyup requests a PHP script which accesses a table in a database to find a like string. But in my PHP script, I'm echo'ing some JS/jQuery which I'm not sure is good practice. Below is my code. Am I going about this the right way or am I totally off base? Any suggestions for improvement?
Javascript
$("#search").keyup(function() {
$("#search_results").show("fast");
$.ajax
({
type: "POST",
url: "http://localhost:8888/index.php/welcome/search/" + $("#search").val(),
success: function(html)
{
$("#search_results").html(html);
}
});
});
PHP
function search($search_string = false)
{
if ($search_string)
{
$this->db->like('name', $search_string);
$query = $this->db->get('clients');
if ($query->num_rows() == 0)
{
echo "No client exists.";
}
else
{
foreach ($query->result() as $row)
{
echo '<script>';
echo '
$("#client_results_'.$row->id.'").hide();
$("#'.$row->id.'").toggle(function()
{
$.ajax
({
type: "POST",
url: "http://localhost:8888/index.php/welcome/search_client_ads/" + '.$row->id.',
success: function(html)
{
$("#client_results_'.$row->id.'").html(html).show("fast");
}
});
}, function()
{
$("#client_results_'.$row->id.'").hide("fast").html("");
});';
echo '</script>';
echo '<p><span id="'.$row->id.'">'.$row->name.'</span></p>';
echo '<div id="client_results_'.$row->id.'"></div>';
}
}
}
else
{
echo '';
}
}
function search_client_ads($client_id)
{
$query = $this->db->get_where('online_ads', array('client' => $client_id));
if ($query->num_rows() == 0)
{
echo "No ads exist.";
}
else
{
foreach ($query->result() as $row)
{
echo $row->id;
}
}
}
Instead of returning numerous scripts, try returning a json string and having jquery loop through it.
精彩评论