I have an html form with a multiple select box. I can't figure out how to send the values to my php application with AJAX via a post request. It works just fine if I use a GET request and use a single select box but not when I use a multiple select box. The idea is for users to hold control (or command with mac) and select one or more categories. Depending on which categories are selected will determine what other form options will be displayed using AJAX. The select box looks like this:
Edit: SOLVED
<select multiple name="categories[]" onclick="sendCategories(this)">
<option value="0">Category 1</option>
<option value="1">Category 2</option>
<option value="2">Category 3</option>
</select>
My javascript function looks like this:
function sendCategories(sel){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("my_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var values = $(sel).serialize();
xmlhttp.send(values);
}
You'll have to generate the query string to send in the POST on your own. Here's the HTML tag to use:
And the Javascript function:
Note that I changed the event from
onclick
toonchange
, but that's really up to you whether you want this function to run when the element is clicked, or its value is truly changed...it can reduce some unnecessary calls.This should generate a querystring that is normally used for sending values for a
<select>
with multiple options selected.Here's a jsFiddle that demonstrates how the querystring is being generated here: http://jsfiddle.net/kKWQM/
You can implement the solution however you would like using JS string and array functions. Effectively, the string you need to send to Apache should contain a pattern like:
xxx[]=a&xxx[]=b&xxx[]=c
where the SELECT element's name is
xxx[]
in your form and a, b, and c are three values the user selected.So yes, you are repeating a key name as many times as the user selected a different option in the SELECT.
In JS you can use an array of selected options:
jQuery should make this easier for you. Calling .val() on a wrapped select returns an array of the selected values. You just have to post these to the server:
HTML:
JavaScript:
You can do something like this,
And Make AJAX using JQuery,
And FYI, Netscape event binding model is deprecated, you could use the cross browser event binding like this