首页 > 解决方案 > 在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":"成功添加个人资料详情"}

纯文本。

我希望在没有任何重定向的情况下显示警报消息。

标签: phpjqueryhtmlajaxcodeigniter

解决方案


推荐阅读