I would appreciate some help. I am trying to create a save bookmark plugin through wordpress functions file (all code in one place). The problem is I am unable get the ajax, jquery to work I am not sure what part of it is not working. You click on link and it’ll call ajax and then php where it’ll save the post_id, user_id into the database.
Here’s the code (funtions.php):
echo '<a href="#bookmark" class="bookmark">Bookmark</a>'; add_action('admin_head', 'bookmark_add'); function bookmark_add() { ?> <script type="text/javascript"> jQuery(document).ready(function($) { $(document).on('click', '.bookmark', function(){ console.log('bookmark_save_TEST'); var data = { 'action': 'bookmark_save', 'user_id': 1234, 'post_id': 3049291 }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(bookmark_save.ajax_url, data, function(response) { alert('Got this from the server: ' + response); }); }); </script> <?php } add_action( 'wp_ajax_bookmark_save', 'bookmark_save_callback' ); function bookmark_save_callback() { global $wpdb; $user_id = intval( $_POST['user_id'] ); $post_id = intval( $_POST['post_id'] ); $post_id += 10; echo $post_id; // once the code above works, will uncomment this to add into the database. //$sql = $wpdb->query("INSERT INTO {$wpdb->prefix}wp_bookmarks(`user_id`,`post_id`) VALUES (%s, %d)", $user_id, $post_id); exit(); }
Can someone please tell me what is it that keeps going wrong?
Advertisement
Answer
if you are using in admin area then use “add_action(‘admin_footer’, ‘bookmark_add’);” for frontend “add_action(‘wp_footer’, ‘bookmark_add’); “
also check your action.
'action': 'bookmark_save_callback',
add_action( 'wp_ajax_bookmark_save_callback', 'bookmark_save_callback' ); add_action( 'wp_ajax_nopriv_bookmark_save_callback', 'bookmark_save_callback' );
you can check for more info https://codex.wordpress.org/AJAX_in_Plugins