序列化ajax生成的HTML表单

时间:2016-06-18 13:18:25

标签: javascript php jquery html ajax

我通过AJAX请求生成HTML表单并添加到我现有的HTML文档中。如何在单击保存数据链接后序列化生成的表单。

我已尝试过下面的代码,但它不起作用。

代码:

$(document).on("click", '#save_data', function(event) {         

    // Gather all the form fields
    var form_fields = $("#data_form").serialize();      

    //post form data via ajax  
    $.ajax({

        type: "POST",
        url: "<?php echo site_url('agromet/save_data'); ?>",            
        data: form_fields,
        success: function(data){

        //add success function 


        },
        error: function(xhr,err){
             console.log(xhr.responseText);             
        }

    });



});

Ajax生成形式:

<form id="data_form">
   <input name = "state_id" id = "state_id" type="text" value =  "">
   <input name = "station_id" id = "station_id" type="text" value =  "">
   <br/><p><a id="save_data" class="btn">Save Data</a>  </p>
</form>

1 个答案:

答案 0 :(得分:0)

请试试这个, 我添加了评论细节

JavaScript的:

<script type="text/javascript">
    function postdatas() {
        $.ajax({
            type: 'POST', //Send type 
            url: '<?php echo site_url('agromet/save_data'); ?>', //Your URL
            data: $('#data_form').serialize(), //Selected form for serialize
            success: function (answer) {
                $("#result").html(answer) //here return from send url
            }
        })
    }
</script>

HTML:

<form id="data_form" name="data_form">
   <input name="state_id" id="state_id" type="text" value =  "">
   <input name="station_id" id="station_id" type="text" value =  "">
   <br/>
   <p>
   <button type="button" onclick="postdatas();" class="btn btn-primary">Gönder</button> <!-- here added onclick tag for submit the form -->
   <br><span id="result"></span>
   </p>
</form>