Created
June 2, 2022 23:06
-
-
Save akshuvo/ea3fce2e48912b4d7508874b897941f4 to your computer and use it in GitHub Desktop.
WordPress Ajax Form Submit Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="my-form-wrap"> | |
<form class="custom-form-class" action="#" autocomplete="off" method="POST"> | |
<!-- Action is here but hidden. This will be use in php side --> | |
<input type="hidden" name="action" value="sample_custom_form_action"> | |
<input class="input" type="text" spellcheck="false" name="name" placeholder="Name" required> | |
<input class="input" type="email" spellcheck="false" name="email" placeholder="E-mail" required> | |
<label class="ans">Yes | |
<input type="radio" name="radio"> | |
<span class="checkmark"></span> | |
</label> | |
<label class="ans">No | |
<input type="radio" name="radio"> | |
<span class="checkmark"></span> | |
</label> | |
<button> SUBMIT </button> | |
</form> | |
</div> | |
<script> | |
// Javascript to send ajax request | |
jQuery(document).on('submit', '.custom-form-class', function(e){ | |
let formData = jQuery(this).serialize(); | |
// Change ajax url value to your domain | |
let ajaxurl = 'http://YOURSITE.COM/wp-admin/admin-ajax.php'; | |
// Send ajax | |
jQuery.post(ajaxurl, data, function(response) { | |
alert('Got this from the server: ' + response); | |
}); | |
}); | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'wp_ajax_sample_custom_form_action', 'prefix_save_custom_form_data' ); | |
add_action( 'wp_ajax_nopriv_sample_custom_form_action', 'prefix_save_custom_form_data' ); | |
function prefix_save_custom_form_data(){ | |
global $wpdb; | |
// Get the values | |
$name = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : ''; // Empty value if data not set | |
$email = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : ''; // Empty value if data not set | |
$radio = isset( $_POST['radio'] ) ? sanitize_text_field( $_POST['radio'] ) : ''; // Empty value if data not set | |
// Assume your table name is wp_customform | |
$your_table_name = $wpdb->prefix . 'customform'; | |
// Insert into database | |
$wpdb->insert( | |
$your_table_name, | |
array( | |
'name' => $name, | |
'email' => $email, | |
'radio' => $radio, | |
) | |
); | |
// Send insert id as ajax response | |
echo $wpdb->insert_id; | |
// Use die to stop the ajax action | |
wp_die(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment