In WordPress, I'm trying to insert data into database using Ajax.
functions.php
function dataInsert(){
global $wpdb, $slidecount;
$slidecount = 25;
$wpdb->insert(
'custom_table',
array(
'slidecount'=> $slidecount
)
);
die();
return true;
}
add_action('wp_ajax_dataInsert', 'dataInsert');
add_action('wp_ajax_nopriv_dataInsert', 'dataInsert');
JavaScript// I put insertDataJS function in footer.php
<script>
function insertDataJS(){
console.log("insertDataJS start");
jQuery.ajax({
type: 'POST',
url: dataInsert.ajaxurl,
data: {"action": "dataInsert"},
success: function(data){
//alert(data);
}
});
console.log("insertDataJS end");
}
</script>
When I tried to call the insertDataJS()
function, I get the error messages below:
Uncaught ReferenceError: dataInsert is not defined at insertDataJS ((index):303) at HTMLDivElement. ((index):444) at HTMLDivElement.dispatch (jquery.js?ver=1.12.4:3) at HTMLDivElement.r.handle (jquery.js?ver=1.12.4:3) at Object.trigger (jquery.js?ver=1.12.4:3) at n.fn.init.triggerHandler (jquery.js?ver=1.12.4:3) at Object.changeTo (eval at (layerslider.kreaturamedia.jquery.js?ver=6.7.6:13), :1:53999) at Object.eval (eval at (layerslider.kreaturamedia.jquery.js?ver=6.7.6:13), :1:131795) at Object.g._callback (greensock.js?ver=1.19.0:20) at Object.g.render (greensock.js?ver=1.19.0:21)
Please share any idea!
As @Inazo and @Outsource suggested in their answer, I sloved it by using the ajaxurl javascript variable to reference the admin-ajax.php file. I declared this on the front end, by putting the following in the footer.php of my theme.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>