I am using this code for data sent by Ajax. I am using summernote editor. My problem is when I submit by missing any field, my from shows 'required alert' and then when I fill all fields and press submit button then the form sends an Ajax request two times. Until it happens every time I miss required field.
<script type="text/javascript">
jQuery(document).ready(function (e) {
jQuery('#btnSubmit').click(function(){ //btnSubmit is submit button id
jQuery("#my_form").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = jQuery(this).attr("action"); //get form action url
var request_method = jQuery(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
jQuery.ajax({
url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",
type: request_method,
data : form_data,
contentType: false,
cache: false,
processData:false,
success:function(data){
alert ('Data Successfully Inserted');
//location.reload();
//top.location.href="admin.php?page=data_list";
},
})
});
})
});
</script>
You can extract the submit out of the click. Write a function that would submit the form, and call it when the #btnSubmit
is clicked. Below is the code to help you:
jQuery('#btnSubmit').on('click', function(event) { event.preventDefault(); //prevent default action submitForm(); }) function submitForm() { var post_url = jQuery("#my_form").attr("action"); //get form action url var request_method = jQuery("#my_form").attr("method"); //get form GET/POST method var form = $('form').get(0); var form_data = new FormData(form) //Creates new FormData object jQuery.ajax({ url: "/demo/wp-admin/admin-ajax.php?action=theme_submit", type: request_method, data: form_data, contentType: false, cache: false, processData: false, success: function(data) { alert('Data Successfully Inserted'); //location.reload(); //top.location.href="admin.php?page=data_list"; }, }) }
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.