使用AJAX和带有Codeigniter的jquery将表单数据传递给控制器 [英] Passing form data to controller using AJAX and jquery with Codeigniter

查看:149
本文介绍了使用AJAX和带有Codeigniter的jquery将表单数据传递给控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to post the data from this form into the database. I have tried some tutorials with no success. Here is my code. Any ideas?

查看:

<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(在视图中,在表格的正下方)

AJAX (in the view, right below the form)

<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>

控制器

  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是未定义的错误,因为您没有将事件引用传递给点击处理程序:

As @David Knipe already said, you should wait for the DOM to be ready before trying to access one of its elements. Moreover, you likely have an e is undefined error, since you're not passing the event reference to the click handler:

<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>

为了更加完整,您的查询是易受攻击的,并且那里可能会出现错误.利用在您下方拥有框架的优势:

To be more complete, your query is vulnerable, and you might be getting an error there. Make use of the advantage of having a framework beneath you:

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

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

^_ I'm guessing the column names since you didn't specify them

这篇关于使用AJAX和带有Codeigniter的jquery将表单数据传递给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆