gpt4 book ai didi

php - 使用 Codeigniter 使用 AJAX 和 jquery 将表单数据传递给 Controller

转载 作者:搜寻专家 更新时间:2023-10-30 20:01:57 25 4
gpt4 key购买 nike

我正在尝试将此表单中的数据发布到数据库中。我尝试了一些教程但没有成功。这是我的代码。有什么想法吗?

查看:

<form method="post" name="myForm1" id="myForm1" enctype="multipart/form-data" >
Email: <input type="text" name="email" id="email">
Question: <input type="text" name="qText" id="qText">
<input id="submitbutton" type="submit">
</form>

AJAX(在 View 中,在表单的正下方)

<script type='text/javascript' language='javascript'>

$("#submitbutton").click(function(){


$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
},
error: function(){
alert("Fail")
}
});
e.preventDefault();
});


</script>

Controller

  function insert_into_db(){
$this->load->model('insert_db');
$this->insert_db->insertQ();
}

模型

 class Insert_db extends CI_Model{

function insertQ(){
$email = $_POST['email'];
$qText = $_POST['qText'];
$this->db->query("INSERT INTO questions VALUES('','$email','$qText','','')");
}
}

最佳答案

正如@David Knipe 所说,您应该等待 DOM 准备就绪,然后再尝试访问其元素之一。此外,您可能有一个 e is undefined 错误,因为您没有将事件引用传递给点击处理程序:

<script>   //no need to specify the language
$(function(){
$("#submitbutton").click(function(e){ // passing down the event

$.ajax({
url:'http://localhost:8888/index.php/trial/insert_into_db',
type: 'POST',
data: $("#myForm1").serialize(),
success: function(){
alert("success");
$('#email').val('');
$('#qText').val('');
},
error: function(){
alert("Fail")
}
});
e.preventDefault(); // could also use: return false;
});
});
</script>

更完整地说,您的查询很容易受到攻击,您可能会在那里遇到错误。利用在您下方拥有框架的优势:

function insertQ(){
$email = $this->input->post('email');
$qText = $this->input->post('qText');
$this->db->insert('questions', array('email' =>$email, 'text' => $text));
}

^_ 我猜是列名,因为你没有指定它们

关于php - 使用 Codeigniter 使用 AJAX 和 jquery 将表单数据传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21004315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com