[英]Codeigniter + Ajax, can't submit form multiple times without page refresh
我試圖在一個頁面中完成簡單的任務,並避免使用 ajax 在每個表單提交時刷新頁面。 問題是我只能向數據庫提交一次更新,而 rest 只是控制台日志成功而不更新數據庫。
Controller
function index() {
$data['process'] = $this->Debug_model->getProcess();
$this->load->view('debug', $data);
}
function nextLine() {
$this->form_validation->set_rules('id', 'ID', 'required');
if ($this->form_validation->run() == FALSE)
{
redirect('debug','refresh');
} else {
$data = array(
'currentLine' => $this->input->post('currentLine'),
'nextLine' => $this->input->post('nextLine')
);
$id = $this->input->post('id');
$this->Debug_model->goNext($data, $id);
}
}
Model
function goNext($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('tbl_process', $data);
}
Javascript
$(document).ready(function() { finish(); }); function finish() { setTimeout(function() { update(); finish(); }, 200); } function update() { $.getJSON("apitest", function(data) { $("#currentLine").empty(); $("#nextLine").empty(); $.each(data.result, function() { $("#currentLine").append( "" + this['currentLine'] + "-" + this['deskNo'] + "" ); $("#nextLine").append( "" + this['nextLine'] + "-" + this['deskNo'] + "" ); }); }); } //btn save $("#btnSave").click(function(e){ e.preventDefault(); var data = $('#callLine').serialize(); $.ajax({ type: 'POST', url: "<?php echo base_url('debug/nextLine'); ?>", data: data, success: function() { console.log('success'); } }); });
看法
<h1>Current: <span id="currentLine"></span></h1> <h2>Next: <span id="nextLine"></span></h2> <?php foreach ($process->result() as $singleProcess): $tobeCurrent = $singleProcess->currentLine + 1; $tobeNext = $tobeCurrent + 1; ?> <form action="" method="post" enctype="multipart/form-data" id="callLine"> <input type="hidden" name="id" value="<?php echo $singleProcess->id?>" /> <input type="hidden" name="currentLine" value="<?php echo $tobeCurrent?>" /> <input type="hidden" name="nextLine" value="<?php echo $tobeNext?>" /> <button id="btnSave" class="btn-a" type="btn">NEXT LINE</button> </form> <?php endforeach; ?>
目標是提交表單時不刷新頁面,並且可以多次完成,仍然不刷新頁面。
不是在按鈕單擊時檢測事件,而是在表單submit
事件中檢測它。
$("#callLine").submit(function(e){
e.preventDefault();
var data = $('#callLine').serialize();
$.ajax({
type: 'POST',
url: "<?php echo base_url('debug/nextLine'); ?>",
data: data,
success: function() {
console.log('success');
}
});
});
還將按鈕類型更改為submit
而不是btn
<button id="btnSave" class="btn-a" type="submit">NEXT LINE</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.