Reputation: 1839
I have a php-ajax page that where user writes search string in search.php, and the list is echoed in getsearch.php. and the result of getsearch.php is show in search.php in using ajax But there is check box in every row.
getsearch.php
$q = $_GET["q"];
$sql = "select hobbyid,hobby from hobbies where hobby LIKE '%".$q."%' ";
if($result=mysql_query($sql))
{
while($row=mysql_fetch_assoc($result))
{
$v = $row['hobbyid'];
echo $row['hobby'] . '<input type="checkbox" name="hobby[]" value='.$v.'>';
}
}
And you can see in following code , this sql is fired for every change(onkeyup). I have kept a check box to get array of selected hobbies. These are selected values are passed to updatehobby.php.
search.php
echo '<form action="updatehobby.php" method="POST">
echo 'Search:<input type="text" onkeyup="showSearch(this.value)" />
<div id="txtSearch" >HERE THE RESULTS FROM getsearch.php are shown</div>
<input type="submit></form>';
So when the user writes a new search string, the list gets changed and so the previous check boxes are deselected. So how can i retain the previous check boxes and display them even if the search changes?
Ultimately after 1 day trying, I successfully did this way!
See user enters search string in search.php and the query is passed to getsearch.php and from there the results are echoed and this results are shown in search.php
So instead of using check box, i inserted a button. So every row now has a button instead of checkbox.
<button type="button" onClick="submitform(<?php echo $row['hobbyid']; ? >);">Add hobby</button>
Now in search.php i again used another ajax function (submitform) which handled the onclick call of button. When the button add hobby is pressed, ajax function submitform is called and the hobby is inserted.
So basically i used two ajax functions in search.php , one ajax for searching and populating results and another for updating it to database.
Upvotes: 4
Views: 1357
Reputation: 12815
(1) You may send checkboxes state in your search request and set checked/not checked in PHP code and include it in your request to database so it will be like
"select hobbyid,hobby from hobbies
where hobby LIKE '%".$q."%' or hobbyid in(list_of_hobbies_received_in_request) "
than, in your loop where you render an HTML - check if id is in received array of ids and set checked state for required hobbies.
(2) Or you can remeber checkboxes state before you send request in javascript and after response came - avoid deleting selected checkboxes and check that there is no duplicates. But it looks like that will be a big pain with how you are getting search results. So, I think (1) is what you need.
Upvotes: 2