Live search results as you type... am I going about this the right way? jQuery + PHP
<p>This is my first time building a tool like this, so please bare with me. I'm doing this to learn more about jQuery and AJAX.</p>

<p>Basically, 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.</p>

<p>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?</p>

<p><strong>Javascript</strong></p>

<pre><code>$("#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);
  }
 });
});
</code></pre>

<p><strong>PHP</strong></p>

<pre><code>function search($search_string = false)
    {
 if ($search_string)
 {
  $this-&gt;db-&gt;like('name', $search_string);
  $query = $this-&gt;db-&gt;get('clients');

  if ($query-&gt;num_rows() == 0)
  {
   echo "No client exists.";
  }
  else
  {
   foreach ($query-&gt;result() as $row)
   {
    echo '&lt;script&gt;';
    echo '
    $("#client_results_'.$row-&gt;id.'").hide();
    $("#'.$row-&gt;id.'").toggle(function()
    {
     $.ajax
     ({
      type: "POST",
      url: "http://localhost:8888/index.php/welcome/search_client_ads/" + '.$row-&gt;id.',
      success: function(html)
      {
       $("#client_results_'.$row-&gt;id.'").html(html).show("fast");
      }
     });
    }, function()
    {
     $("#client_results_'.$row-&gt;id.'").hide("fast").html("");
    });';
    echo '&lt;/script&gt;';
    echo '&lt;p&gt;&lt;span id="'.$row-&gt;id.'"&gt;'.$row-&gt;name.'&lt;/span&gt;&lt;/p&gt;';
    echo '&lt;div id="client_results_'.$row-&gt;id.'"&gt;&lt;/div&gt;';
   }
  }
 }
 else
 {
  echo '';
 }
}

function search_client_ads($client_id)
    {
 $query = $this-&gt;db-&gt;get_where('online_ads', array('client' =&gt; $client_id));

 if ($query-&gt;num_rows() == 0)
 {
  echo "No ads exist.";
 }
 else
 {
  foreach ($query-&gt;result() as $row)
  {
   echo $row-&gt;id;
  }
 }
}
</code></pre>
