AJAX form not working, still reloads on submit

I’ve built a like and unlike system for users, and it works amazingly. The only problem is the page reloads, therefore, I’ve tried to set up AJAX to submit the form without a page refresh. However, it’s still not working and the submit button still refreshes the page.

Maybe I am doing something wrong here?

functions.php

function op_scripts() {
wp_enqueue_script( ‘op-ajax’, admin_url( ‘admin-ajax.php’ ) );wp_enqueue_script( ‘op-post-like-ajax’, get_template_directory_uri() . ‘/ext/js/post_like_ajax.js’ );
}
add_action( ‘wp_enqueue_scripts’, ‘op_scripts’ );

Here I’m calling the admin AJAX, which is what I was told to do by a fellow developer friend – maybe this is where I am going wrong?

post_like_ajax.js

jQuery(document).ready(function( $ ) {

$(‘#like-post’).submit(function(e){
$.ajax({
data: {action: ‘like_post’, name: ‘like_post’},
type: ‘post’,
url: ajaxurl,
success: function(data) {
alert(data);
}
});
};

$(‘#unlike-post’).submit(function(e){
$.ajax({
data: {action: ‘unlike_post’, name: ‘unlike_post’},
type: ‘post’,
url: ajaxurl,
success: function(data) {
alert(data);
}
});
};

});

post_like.php

function post_likes() {
if( is_user_logged_in() ){
global $post;
$post_id = $post->ID;
global $current_user;
$user_id = $current_user->ID;
$liked_user_id = get_post_meta($post_id, ‘_post_likes’, true); ?>
<div id=”post-options”>
<div id=”post-likes”>
<?php if( $user_id == $liked_user_id ){ ?>
<form name=”like_post” id=”like_post” method=”POST” action=”like_post”>
<button type=”submit” name=”unlike_post_<?php echo $post_id ?>”><i class=”fa fa-heart”></i></button>
</form>
<?php if(isset($_POST[‘unlike_post_’ . $post_id])){
delete_post_meta($post_id, ‘_post_likes’, $user_id);
}
} elseif( $user_id != $liked_user_id ) { ?>
<form name=”unlike_post” id=”unlike_post” method=”POST” action=”unlike_post”>
<button type=”submit” name=”like_post_<?php echo $post_id ?>”><i class=”fa fa-heart-o”></i></button>
</form>
<?php if(isset($_POST[‘like_post_’ . $post_id])){
add_post_meta($post_id, ‘_post_likes’, $user_id);
}
} ?>
</div>
</div>
<?php }

}
add_action(‘wp_ajax_post_likes’, ‘post_likes’);
add_action(‘wp_ajax_nopriv_post_likes’, ‘post_likes’);

It’s a pretty clean system besides the AJAX not working, but I just need it to not refresh the page upon liking and unliking the post otherwise the user will lose where they are down the page.

Can anyone help me with this please?

Read more here:: AJAX form not working, still reloads on submit

Leave a Reply

Your email address will not be published. Required fields are marked *