jeudi 29 janvier 2015

Wordpress custom plugin ajax request not working


I wrote a jQuery ajax request. I've read the documentation regarding ajax requests and frankly it's not working for me.


I got it to a point that it is hitting the function and returning something.


This is the Ajax request:



jQuery('#ns-submit-comment').on('click',function(e) {
e.preventDefault();
jQuery('#comment-loader').show();

var data = {
'action': 'submit_comment',
'new-comment': jQuery('#new-comment').val(),
'ajax': true
};

jQuery.post(jQuery(this).parent('form').attr('action'), data, function(response) {
data = JSON.parse(response);
alert(data);
jQuery('<p style="margin-bottom:0px;"><b>' + data.author + '</b> <small class="pull-right"><i>' + data.time + '</i></small><br>' + jQuery('#new-comment').val() + '</p>').insertAfter('#comment-header');
jQuery('#new-comment').val('');
jQuery('#comment-loader').hide();
});
});


This is my action:



add_action( 'wp_ajax_submit_comment', 'save_comment' );


And this is my function that handles the Ajax request:



function save_comment($user_id, $article_id)
{
if (empty($article_id) || !is_numeric($article_id)) {
wp_redirect(home_url());
exit;
}

$comment = $_POST['new-comment'];

if (empty($comment)) {
if(isset($_POST['ajax'])) {
return json_encode(['success'=>false,'error'=>'Comment Empty']);
} else {
wp_redirect(get_site_url() . '/author-history/');
}
}

$user = get_userdata($user_id);

$time = current_time('mysql');

$data = [
'comment_post_ID' => $article_id,
'comment_author' => $user->data->user_login,
'comment_author_email' => $user->data->user_email,
'comment_author_url' => $user->data->user_url,
'comment_content' => $comment,
'comment_type' => 'editorial-comment',
'comment_parent' => 0,
'user_id' => $user->data->ID,
'comment_author_IP' => $_SERVER['REMOTE_ADDR'],
'comment_agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)',
'comment_date' => $time,
'comment_approved' => 'editorial-comment',
];

$comment_result = wp_insert_comment($data);

// update_post_meta($parent_article, "latest_revisions", [$post_id]);
if(isset($_POST['ajax'])) {
die(debug($data));
return json_encode(['time'=>$time, 'author' => $user->data->user_login]);
} else {
wp_redirect(get_site_url() . '/author-history');
}
}


Now all goes well until it hits the alert, where it returns the whole page. I use die(debug($data)) (debug is a custom debugger function) and that returns the whole page. How do I prevent it from returning the whole page and only make it return the data?





Aucun commentaire:

Enregistrer un commentaire