[英]How to insert into database using AJAX, PHP and CodeIgniter?
Please tell me how to use AJAX with CodeIgniter. 请告诉我如何在CodeIgniter中使用AJAX。 I wrote the view like this but I am not sure how to send data to model with the controller.
我写了这样的视图,但不确定如何使用控制器发送数据以进行建模。
My view is: 我的看法是:
<html>
<head>
<script>
function insert(fname,lname,age)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_db_php.php?fname=fname&lname=lname&age=age",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<table>
<tr><td>First Name : </td><td> <input type="text" fname="fname"/> </td> </tr>
<tr><td>Last Name : </td><td> <input type="text" fname="lname"/> </td> </tr>
<tr><td>City : </td><td> <input type="text" fname="age"/> </td> </tr>
<input type="button" onclick="insert(fname,lname,age)">
</table>
</form>
</body>
</html>
Please help me with writing the controller and model for this case. 请帮助我编写这种情况的控制器和模型。
This is the idea: 这是个主意:
Better use post
for submitting forms using ajax: 更好地使用
post
使用ajax提交表单:
xmlhttp.open("POST","user_ajax",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname="+fname+"&lname="+lname+"&city="+city);
Model 模型
class user extends CI_Model{
function insert(){
$data = array(
"fname" => $this->input->post('fname'),
"lname" => $this->input->post('lname'),
"city" => $this->input->post('city')
);
return $this->db->insert("TABLE_NAME",$data);
}
}
Controller 调节器
class user_ajax extends CI_Controller{
function index(){
$this->load->model("user");
if(isset($_POST['fname'])){
$ths->user->insert();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.