I'm trying to pass multiple checkboxes with different values to a PHP script that will run a search against my database for the values that are selected.
The HTML form is as follows:
<li><input type="checkbox" class="keywords" value="option1" title="option1" /></li>
<li><input type="checkbox" class="keywords" value="option2" title="option2" /></li>
<li><input type="checkbox" class="keywords" value="option3" title="option3" /></li>
<li><input type="checkbox" class="keywords" value="option4" title="option4" /></li>
<li><input type="submit" name="submit" class="search" /></li>
The javascript code to pass this to my PHP file is:
<script type="text/javascript">
$(document).ready(function(){
$(".search").click(function()
{
$.post("parser.php",
{
keywords: $(".keywords:checked").val()
},
function(data)
{
$.each(data, function()
{
$("div#result").append("<li class='arrow'><a href='parser.php?id=" + this.id + "'>" + this.title + "</a></li>");
});
$("div#jsonContent").show();
},
"json");
});
});
</script>
In parser.php I then take the incoming keyword, and search the database:
$keywords = mysql_real_escape_string ($_GET["keywords"]);
$query = mysql_query("SELECT * FROM keyworddb WHERE keywords LIKE '%". $keywords ."%' ");
$arr = array();
while( $row = mysql_fetch_array ( $query ) )
{
$arr[] = array( "id" => $row["id"], "title" => $row["title"] );
}
echo json_encode($arr);
This is all great, it runs through without any errors except:
1) In firebug it's sending over the selected checkbox value, though not the multiple checkboxes. It only uses the first checkbox value if multiple checkboxes selected.
2) Despite that it returns all entries to the table :( no matter what is selected.
Any help appreciated.
Update:
I've made the chanegs suggested:
<form id="findkeywords">
<ul>
<li><input type="checkbox" class="keywords[]" value="option1" title="option 1" /></li>
<li><input type="checkbox" class="keywords[]" value="option2" title="option 2" /></li>
<li><input type="checkbox" class="keywords[]" value="option3" title="option 3" /></li>
<li><input type="checkbox" class="keywords[]" value="option4" title="option 4" /></li>
<li><input type="submit" name="submit" class="search" /></li>
</ul>
</form>
The Javascript has been changed to:
$(document).ready(function(){
$(".search").click(function()
{
$.post("parser.php",
{
keywords: $("form#findkeywords").serialize()
},
function(data)
{
$.each(data, function()
{
$("div#result").append("<li class='arrow'><a href='parser.php?id=" + this.id + "'>" + this.title + "</a></li>");
});
$("div#jsonContent").show();
},
"json");
});
});
I haven't made any additional changes to the php file yet as I just want to make sure this is actually sending the data across. But in FireBug it doesn't appear to be sending anything at all.