This way to insert data in db using AJAX works for me. Hope this help you.
Function scripts
function add_our_script() {
wp_register_script( 'ajax-js', get_template_directory_uri() . '/scripts/keeled.js', array( 'jquery' ), '', true );
wp_localize_script( 'ajax-js', 'ajax-js_ajax', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'add_our_script' );
Template Form:
<form>
<label for="nimi">Nimi</label>
<input name="nimi" id="nimi" type="text"/>
<input id="nimi_submit" type="button" value="Send">
</form>
In keeled.js
jQuery('#nimi_submit').click( function () {
var nimi = jQuery('#nimi').val();
jQuery.ajax({
url: ajax-js_ajax.ajax_url,
type: "POST",
data: {
'action': 'post_language',
'nimi': nimi,
},
success: function (data) {
alert(data);
}
});
});
Callback action
function post_language(){
global $wpdb;
$nimi = isset( $_POST['nimi'] ) ? $_POST['nimi'] : '';
$table="voorkeel";
$wpdb->insert( $table, array('nimi' => $nimi));
}
add_action('wp_ajax_post_language', 'post_language');