[英]Unable to post select multiple using jQuery .ajax() to php codeIgniter
我正在嘗試將select元素的多個值發布到php,僅在.ajax發布中給出錯誤。 與HTML表單發布一起使用時效果很好。
JS:
function serealizeSelects(select){
var array = [];
select.each(function(){ array.push($(this).val()) });
return array;
}
$("#go").on('click', function(e){
e.preventDefault();
if($("#title").val()=='') swal('','Please enter the title.','warning');
else{
$("#go").text('Publishing...');
$("#go").prop('disabled',true);
$.ajax({
url: '<?=base_url();?>'+'classes/add_notes',
type: "POST",
data: {
title: $("#title").val(),
content: $("#content").val(),
file: upFile,
class: JSON.stringify(serealizeSelects($('.selectpicker'))),
<?=$this->security->get_csrf_token_name();?>:'<?=$this->security->get_csrf_hash();?>',
},
dataType: "json",
success: function(data){
$("#go").text('Publish');
$("#go").prop('disabled',false);
if(data.error=='false'){
swal('Published','Your notes has been shared to selected classes.');
}
else{
if(data.error_code=='1') swal('','Please fill fields properly!','warning');
else if(data.error_code=='2') swal('','Unauthorised','error');
else swal('','Something went wrong','error');
}
},
error: function(){
$("#go").text('Publish');
$("#go").prop('disabled',false);
swal('','Some error occured','error');
}
});
}
});
HTML:
<select class="selectpicker" data-live-search="true" id="class" multiple>
<option value="0">Choose classes...</option>
<?=$classes;?>
</select>
** PHP(CodeIgniter):**
$this->form_validation->set_rules('title', 'title', 'trim|required|xss_clean');
$this->form_validation->set_rules('content', 'content', 'trim|xss_clean');
$this->form_validation->set_rules('file', 'file', 'trim|xss_clean');
$this->form_validation->set_rules('class[]', 'class', 'trim|required|xss_clean');
if($this->form_validation->run() == FALSE OR $this->end!='teacher'){
$response['error']="true";
$response['error_code']="1";
}
else{
$title=$this->input->post('title');
$content=$this->input->post('content');
$file=$this->input->post('file');
$classes=json_decode($this->input->post('class[]'),true);
foreach($classes as $class){
// Some task
}
}
我一直在尋找很多解決方案,但是都沒有用。 我也嘗試了class ,而不是class [] 。 沒事! 發布此消息將執行ajax的錯誤部分。
進行以下更改:
<select class="selectpicker" data-live-search="true" id="class" multiple>
至
<select name="selectpicker[]" class="selectpicker" data-live-search="true" id="class" multiple>
並獲得其值,例如:
$this->input->post('selectpicker');
說明:對於multi-select dropdown
,其名稱必須為和數組,如selectpicker[]
以便它可以在其中保存多個選定值並通過在php中使用其名稱來獲取其值。
嘗試 $this->input->post('class[]'),true);
您永遠無法使用其類直接在php中獲取html元素值 $this->input->post('class[]'),true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.