我想在Modal中显示表单验证错误,但错误会显示在新页面中
查看
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="modelError">hi</div>
<?php echo form_open('welcome/add_data','id="myform"'); ?>
<div class="form-group">
<label for="user_name" class="col-sm-4 control-label">User Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="user_name" id="user_name">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="name" id="name">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="add">Save</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function () {
$(document).on('submit','#myform',function(event){
event.preventDefault();
let name=$("#name").val();
let user_name=$("#user_name").val();
$.ajax({
url:"<?php echo base_url(). 'welcome/add_data';?>",
method: 'POST',
data:new FormData(this),
contentType:false,
processData:false,
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
}
});
})
})
</script>
控制器
public function add_data(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('user_name', 'User Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}
else {
$data=array(
'name'=>$this->input->post('name'),
'user_name'=>$this->input->post('user_name'),
);
$this->Test_model->add_data($data);
redirect('welcome',"refresh");
}
}
我希望模态(弹出窗口)中出现错误,但是这些错误会显示在新页面“ localhost / ajax / welcome / add_data”中
我已经尝试了很多来自stackoverflow的代码段,但是它们都不起作用。