为什么ajax在成功或错误后会继续重定向到其他页面

时间:2018-04-21 19:22:54

标签: php jquery ajax codeigniter

我是ajax的新手,现在我想使用ajax,因此在添加数据并显示错误或成功消息时,我的页面不会重新加载。但在实现中,当我提交表单时,它会将我重定向到另一个页面,其中包含表单验证错误/成功消息。我试图解决这个问题,但我无法找到错误。我使用的是Jquery 1.8.3和codeigniter。这是我的代码。

Custom.js

function tambahBuku() {
$('#form_tambah')[0].reset();
$('#form_tambah').unbind('submit').bind('submit',function() {
var form = $(this);

  $.ajax({
    url: "http://localhost:8000/prjperpus-ci/Table/tambah",
    type: "POST",
    data : form.serialize(), //converting the form data into array and sending it to server
    dataType : "json",
    success:function(response, xhr, ajaxOptions, thrownError){
        alert("OKAY"); alert(xhr.status);
      if(response.success == true){
            alert("OK");
        $(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">' +
        '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
        '<strong><span class="glyphicon glyphicon-ok-sign"> </span></strong>' + response.messages + '</div>')
      } else{
        if(response.messages instanceof Array){
          $.each(response.messages, function(index,value) {
            alert(index);
          });
        } else {
          alert("OK else");
          $(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">' +
          '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
          '<strong><span class="glyphicon glyphicon-exclamination-sign"> </span></strong>' + response.messages + '</div>')
        }
      }
    },   error: function(xhr, ajaxOptions, thrownError){
        alert("ERROR");
            alert(xhr.readyState);
        }
  })
});

}

查看

 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#tambah" onclick="tambahBuku()">Tambah Buku</button>
 <div class="messages"></div>

<div class="modal fade" id="tambah" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
    <div class="modal-content">
       <div class="modal-header">
           <h3 class="modal-title" id="exampleModalLabel">Input Buku</h3>
             <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
             </button>
       </div>
             <?php $attributes = array('id' => 'form_tambah','method' => 'POST');
                 echo form_open('Table/tambah', $attributes); ?>
                   <div class="modal-body">
                      <div class="form-group">
                          <label>ISBN</label>
                          <input type="text" class="form-control" id="" placeholder="ISBN" name="isbn">
                      </div>
                      <div class="form-group">
                          <label>Judul Buku</label>
                          <input type="text" class="form-control" id="" placeholder="Judul Buku" name="judul">
                      </div>
                  </div>
                  <div class="modal-footer">
                     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                     <button type="submit" class="btn btn-primary" onclick="">Save changes</button>
                  </div>
             <?php echo form_close(); ?>
     </div> 
</div> 
</div>

控制器(Table.php)

  public function tambah()
  {
        $data = array(
          'ISBN' => $this->input->post('isbn'),
          'Judul_Buku' => $this->input->post('judul'),
        );

        $config = array(
          array(
            'field' => 'isbn',
            'label' => 'ISBN',
            'rules' => 'trim|required'
          ),
          array(
            'field' => 'judul',
            'label' => 'Judul buku',
            'rules' => 'trim|required|is_unique[buku.Judul_Buku]'
          )
       };
         $this->form_validation->set_rules($config);

   $validator = array('success' => false , 'messages' => array());
   if($this->form_validation->run() === TRUE){
     $insert_Book = $this->action->insert_record("buku",$data);

     if($insert_Book == true){
        $validator['success'] = true;
        $validator['messages'] = "Data sukses ditambahkan";
        var_dump($validator);
     } else{
       $validator['success'] = false;
       $validator['messages'] = "Data gagal ditambahkan";
     }    
   }else{
     $validator['success'] = false;
     foreach ($_POST as $key => $value) {
      $validator['messages'][$key] = form_error($key);
     }
   }
   echo json_encode($validator);
}

模型(action.php的)

public function get_data($table){
      return $this->db->get($table);
}

public function insert_record($table,$data){
  $sql = $this->db->insert($table, $data);
  if($sql === true){
    return true;
  } else{
    return false;
  }
}

1 个答案:

答案 0 :(得分:0)

如果您使用ajax提交数据,则必须停止提交HTML(这是导致重定向的原因)。
您可以在提交处理程序中使用事件对象的preventDefault方法来完成此操作。

$('#form_tambah').unbind('submit').bind('submit',function(event) {
    event.preventDefault();