php - 在codeigniter中通过ajax post提交表单数据时如何停止重定向到控制器页面
问题描述
我正在尝试使用 Ajax post 将表单数据从视图提交到控制器并返回成功消息。我视图中的 ajax 成功地将数据发送到控制器中的函数,但控制器函数不会将响应返回给 ajax 成功函数。
我的控制器 - profile.php
function save()
{
$response = array();
$this->form_validation->set_rules('fname', 'Title cant be empty ', 'required');
if ($this->form_validation->run() == TRUE)
{
$param = $this->input->post();
unset($param['submit']);
$param['rid']=$this->session->userdata('id');
$profile_id = $param['profile_id'];
unset($param['profile_id']);
if($profile_id == 0)
{
$inserts = $this->profile_model->insert($param);
if( $inserts>0){
$response['status'] = TRUE;
$response['notif'] ="success add profile details";
}else{
$response['status'] = FALSE;
$response['notif'] = 'Server wrong, please save again';
}
}else{
}
}else{
$response['status'] = FALSE;
$response['notif'] = validation_errors();
}
echo json_encode($response);
}
查看 - profile_new_user.php
?>
<form method="POST" id="form_profile" action="<?php echo base_url().'profile/save'; ?>">
<input type="hidden" name="profile_id" value="0"><!-------event id---------->
<div class="form-group">
<label>Prefix</label>
<select name="prefix" class="form-control">
.
.
.
</div>
<div class="form-group">
<input type="submit" name="submit" value="Save" class="btn btn-info" />
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#form_profile").submit(function(event){
event.preventDefault();
$.ajax({
method: "POST",
url: $(this).attr("action"),
dataType :'JSON',
data: $(this).serialize(),
success: function(data)
{
if(data.status){
alert('ok');
}else{
alert('not ok');
}
}
})
});
});
模型 - profile_model.php
function insert($data)
{
$this->db->insert('user_profile', $data);
return $this->db->insert_id();
}
单击提交按钮后,页面重定向到 url - http://localhost/ptm6/profile/save并显示页面
{"status":true,"notif":"成功添加个人资料详情"}
纯文本。
我希望在没有任何重定向的情况下显示警报消息。
解决方案
推荐阅读
- c# - Unity 3d & C#, if gameObject != this
- python - 将多个数据帧与互补缺失值组合的最有效方法
- r - 想要选择满足多个条件的所有行并为其创建子集
- node.js - 使用 UUID npm 模块出现奇怪的错误。我究竟做错了什么?
- angularjs - 具有多个条件的 ng-options
- java - 一旦用户输入小于 0 的数字,如何破坏扫描仪?
- c# - ServiceStack.Redis:配置让请求和响应类/dto是同一个类?
- python - 在非选项命令行参数之后抑制选项处理
- r - 是否有为 RStudio 项目保留研究日记的软件包或其他方便的方法?
- python - Python:Numpy 切片不一起比较/广播。[x:y] vs [0:yx] 声称不同的维度