Controller code I have :
<?php
class Ajax_cntrl extends CI_controller{
public function index(){
$this->load->view('ajax_view');
$insert = array(
'name' => $this->input->post('name'),//<-- also not able to get this id from ajax post request
'pass' => $this->input->post('pass'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->db->insert('form',$insert);//<--insert item into cart
$query;// to insert into database
//redirect('shop');
}
}
?>
查看我的代码::
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Pass</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
pass: $('#pass' + id).val(),
email: $('#email' + id).val(),
mobile: $('#email' + id).val(),
address: $('#email' + id).val()
};
$.ajax({
type:'post',
url:"<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
</script>
问题是,当我提交表单时,它刷新浏览器ajax无法正常工作在哪里是错误m无法理解请帮助我相关的原因为什么ajax调用不在那里工作并且是一种实现ajax的gud方式与codeigniter?如果是,那么它不起作用
答案 0 :(得分:2)
使用以下代码,这将解决您的问题。
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {//repair
name: $('#name').val(),
pass: $('#pass').val(),
email: $('#email').val(),
mobile: $('#mobile').val(),
address: $('#address').val()
};
$.ajax({
type: 'post',
url: "<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data,
dataType: 'json',
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
});
</script>
如果它不适合你,请告诉我。