Daniel Kimani Daniel Kimani - 4 months ago 7
jQuery Question

Serialize ajax generated HTML Form

I am generating an HTML form via AJAX request and add into my existing HTML document. How do i serialize the generated form after clicking the save data link.

I have tried the code below but its not working.


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

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

//post form data via ajax

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

//add success function

error: function(xhr,err){



Ajax generated form:

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


Try this please, I add details with comments


<script type="text/javascript">
    function postdatas() {
            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


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