I have seen a number of methods dating back to about 2011 in order to take a form and have its data posted via ajax.jquery. I have tried a couple and am just getting the page to reload despite using preventdefault functions
.
I am trying to take data from my form, have the jQuery listen for the form submit by targeting the actual form id and then call a PHP function in order to have that data posted to the db. Ultimately nothing happens other than a page reload. Since this is a WP page, I know that some of the functions and handling differ from regular webpages. Things like the ajax url, can be passed back to the functions etc. That is why I Am posting this here.
the form:
function add_entry(){
?>
<form action="" method="post" id="ajax-add-to-form" autocomplete="off">
<input type="text" id="FName" name="FName" placeholder="First Name" value="" required>
<input type="text" id="LName" name="LName" placeholder="Last Name" value="" required>
<select id="size" required>
<option value="">Size</option>
<?php for($i=1; $i<=15; $i++){?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select>
<input type="text" id="MobileNumber" name="MobileNumber" placeholder="Phone Number" value="" required>
<input type="email" id="Customer_Email" name="Customer_Email" placeholder="Email Address" value="" required>
<input type="submit" name="ajax-add-to-form" value="Add to">
<?php
}
add_shortcode('add_entry', 'add_entry');
</form>
the jquery
jQuery('document').ready( function(){
jQuery('#ajax-add-to-form').on('submit', function(e){
e.preventDefault();
jQuery('#jx-loading').show();
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'ajax-php-function'},
success: function(data)
{jQuery('#jx-loading').hide();}
})
});
return false;
});
the php
function ajax-php-function() {
global $wpdb;
$table = "mytablename";
$FName= $_POST['FName'];
$LName= $_POST['LName'];
$MobileNumber= $_POST['MobileNumber'];
$Email = $_POST['Email '];
$data = array(
'FName' => $FName,
'LName' => $LName,
'MobileNumber' => $MobileNumber,
'Email' => $Email);
$success = $wpdb->insert( $table, $data );
if($success)
{echo json_encode($last_data);}
else{ echo 'error'; } die;
}