I have one select box:
<select name="sub_selected" class="bmarks" id="sub_selected"
style="width:400px" size="5">
<option value="1">first value</option>
<option value="2">second value</option>
<option value="4">other vale</option>
</select>
I want to pass all values to php.
I write the following code but it doesn't work:
$('#sub_selected').each(function(i, selected){
foo[i] = $(selected).val();
var title = $('#prop_tile').attr('value');
$.ajax({
type: "POST",
url: "add_process.php",
data: "title="+ title +"& stages="+ foo,
success: function(html){
if (html==1){
$('div.saving').hide();
$('div.success').fadeIn();
}else {
$('div.saving').hide();
$('div.nosuccess').fadeIn();
}
}
});
I want to submit all values of select box to php to store in mysql, preferably in this format (1,2,4).
Thanks
If you really want ALL of them, then don't do it that way. Get them in PHP the same way you got them to display the select options.
I don't know much about jquery but it seems to me you may be able to resolve your issue purely at the HTML level, assuming your jquery simply submits the form that contains your <select>
tag. The way <select>
behaves is that the browser will only submit data in the post that is selected. If the options are not highlighted, they won't be sent to the server in your POST
.
You may be able to resolve it as follows; First of all, your <select>
needs the multiple="multiple"
attribute so that more than one element can be selected. Secondly, add the selected="selected"
attribute to each of the <option>
tags. And lastly, if you don't want the user to unselect any of the options prior to form submission, add the disabled="disabled"
attribute to the <select>
tag.
UPDATE: You may also want to change the name="sub_selected"
to name="sub_selected[]"
so that you can receive the value as an array on the PHP side. You'll need to adjust your jquery references of sub_selected
to sub_selected[]
.
If you really want to do it with jquery, here is the simple/correct way to do it:
// I'm not sure what the '#prop_tile' element is so I didn't
// include it for this example
var all_vals = new Array;
$('#sub_selected option').each(function() {
all_vals.push($(this).val());
});
$.post('add_process.php', { stages:all_vals }, function(html) {
$('div.saving').hide();
$('div.success').fadeIn();
},'html');
On the receiving end, you can do:
<?php
if(isset($_POST['all_vals'])) {
$all_vals = $_POST['all_vals'];
// $all_vals is now an array = [1,2,4]
}
?>
NOTE: It would be nice if you disclosed more details about why you would want to do this because, skin deep, it seems like a silly thing to do.