php CodeIgniter 和 AJAX 表单提交

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17572429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:06:59  来源:igfitidea点击:

CodeIgniter and AJAX form submit

phpjavascriptmysqlajaxcodeigniter

提问by Ty Bailey

I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.

我正在尝试将从表单提交的数据保存到我的 mysql 数据库中,然后使用添加到 div 列表中的最后发布的项目更新 div 元素。

Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.

现在我只是想得到回复,我现在并不担心格式是否正确。

My problem is the form won't submit with e.preventDefault();in place, but without it the form does the normal method of posting to the db then refreshing the page.

我的问题是表单不会e.preventDefault();就地提交,但没有它,表单会执行正常的发布到数据库然后刷新页面的方法。

Here is my AJAX call:

这是我的 AJAX 调用:

$(document).ready(function() {

    $('form#feedInput').submit(function(e) {

        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
            data: $('.feed-input').val(),
            dataType: "html",
            success: function(data){
                debugger;
                $('#feed-container').prepend(data);
            },
            error: function() { alert("Error posting feed."); }
       });

    });
});

I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault();function.

我认为我没有必要发布我的控制器代码,因为我的问题是表单无法通过e.preventDefault();函数。

How can I get this form to submit via AJAX if the e.preventDefault()function is stopping it before it can reach the $.ajax()function?

如果e.preventDefault()函数在到达$.ajax()函数之前停止它,我如何让这个表单通过 AJAX 提交?

回答by Fracsi

The dataattribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() }or in query format 'key='+$('.feed-input').val(). Also there is an unnecessary debuggervariable in the success method.

dataajax 调用的属性无效。它应该是 JSON 格式{ key: $('.feed-input').val() }或查询格式'key='+$('.feed-input').val()debugger在成功方法中还有一个不必要的变量。

A working code could be:

一个工作代码可以是:

$('form#feedInput').submit(function(e) {

    var form = $(this);

    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
        data: form.serialize(), // <--- THIS IS THE CHANGE
        dataType: "html",
        success: function(data){
            $('#feed-container').prepend(data);
        },
        error: function() { alert("Error posting feed."); }
   });

});

回答by Siddharth Shukla

Html part in view

视图中的 HTML 部分

<form id="comment" method="post">
    <h2>Enter Your Details</h2>
    <center><div id="result"></div></center>

    <div class="form_fld">
        <label>Name</label>
        <input type="text" placeholder="Enter Your Full Name" name="name" required=""> 
    </div>
    <div class="form_fld">
        <label>Email ID</label>
        <input type="text" placeholder="Enter Email ID" name="email" required="">
    </div>
    <div class="form_fld">
        <label>Contact Number</label>
        <input type="text" placeholder="Enter Contact Number" name="contact" required="">
    </div>
    <div class="form_fld">
        <label>Developer</label>
        <select name="developer">
            <option>Lotus</option>
            <option>Ekta</option>
            <option>Proviso</option>
            <option>Dosti</option>
            <option>All</option>
        </select>
    </div>
    <div class="form_fld">
        <button type="submit" id="send">Submit</button>
    </div>
</form>

After Html Part Just put ajax request

在 Html 部分之后只放 ajax 请求

<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
    $("#comment").submit(function(){
        dataString = $("#comment").serialize();

        $.ajax({
            type: "POST",
            url: "home/contact",
            data: dataString,
            success: function(data){
                // alert('Successful!');
                $("#result").html('Successfully updated record!'); 
                $("#result").addClass("alert alert-success");
            }

        });

        return false;  //stop the actual form post !important!

    });
});
</script>

Within Controller

控制器内

public function contact()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    $data = array('name' => $this->input->post('name'),
                  'email' => $this->input->post('email'),
                  'number' => $this->input->post('contact'),
                  'developer' => $this->input->post('developer'),
                  'ip' => $ip,
                  'date' =>  date("d/m/Y"));
    $result = $this->User_model->contact($data);
    print_r($result);
}

回答by Robert

You don't have to use preventDefault();you can use return false;in the end of function submit()but I doubt this is the problem.

你不必使用preventDefault();你可以return false;在函数的末尾使用,submit()但我怀疑这是问题所在。

You should also use url encoding on $('.feed-input').val()use encodeURIComponentfor this.

你也应该使用URL编码上$('.feed-input').val()使用encodeURIComponent了这一点。

You should also check if you have errors in your console.

您还应该检查控制台中是否有错误。

To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.

要确定是否阻止了默认操作,您可以使用e.isDefaultPrevented(). 在这种情况下,默认操作是指使用 id feedInput 提交表单的操作。

You didn't name your param in data. Check jquery ajax examples.

您没有在数据中命名您的参数。检查jquery ajax 示例

回答by Nil'z

You are probably getting an error e.preventDefault();is not stopping the ajax.

您可能会收到一个错误,e.preventDefault();即没有停止 ajax。

$.ajax({
    type: "POST",
    url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
    data: $("#form").serializeArray(),
    success: function(resp){
        $('#container').html(resp);
    },
    error: function(resp) { alert(JSON.stringify(resp)); }
});