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.
Code:
$(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 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>
</form>
Try this please, I add details with comments
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.