AJAX commenting in WordPress - javascript

I'm trying to get AJAX commenting working in WordPress. So far I have written a PHP handler and a script.
My script (modified from here):
jQuery(document).ready(function($){
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
//serialize and store form data in a variable
var data=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'POST',
url: formurl,
dataType: 'JSON',
data: data,
error: function(XMLHttpRequest, errorThrown)
{
statusdiv.html('<p class="ajax-error" >Oops, an error occured</p>');
},
success: function(data)
{
statusdiv.html(data);
$('#commentform #comment').val('');
}
});
return false;
});
});
My PHP handler:
function ajaxify_comments( $comment_ID, $comment_status ) {
$comment = get_comment( $comment_ID );
$response = $comment->comment_content;
echo json_encode( $response );
die();
}
add_action( 'comment_post', 'ajaxify_comments', 20, 2 );
My PHP handler, ajaxify_comments(), is hooked to comment_post which fires immediately after the comment is saved to the database. The function gets the comment text and returns a response (the comment text) to my AJAX script. If everything is successful, the comment text is displayed on screen. If unsuccessful, an error message is displayed.
My problem
If I submit a comment, the comment is saved to the database and the comment text is displayed on screen. This bit works! My problem is if I make a second comment without refreshing the page - I always get "Oops, an error occurred". What am I doing wrong?
Update
After #adeneo's suggestion to use the WordPress built in AJAX hooks I have come up with a new script and PHP handler...
Script:
jQuery(document).ready(function($) {
var path = ac.path;
var security = ac.security;
var ajax_url = ac.ajax_url;
var commentform = $('#commentform');
commentform.prepend('<div id="comment-status"></div>');
var statusdiv = $('#comment-status');
commentform.submit(function(){
$.ajax({
type: 'POST',
url: ajax_url,
dataType: 'JSON',
data: {
'action': 'ac',
'security': security
},
success:function(data) {
statusdiv.html(data);
$('#commentform #comment').val('');
},
error: function(data){
statusdiv.html('<p class="ajax-error">Oops, an AJAX error occured</p>');
}
});
return false;
});
});
PHP handler
function ajaxify_comments() {
check_ajax_referer( 'ajax_ac_nonce', 'security' );
$response = 'blah';
echo json_encode( $response );
die();
}
add_action( 'wp_ajax_ac', 'ajaxify_comments' );
For completeness it is worth letting you know that I also have:
wp_enqueue_script( 'ac-script', plugins_url( '/js/script.js', __FILE__ ), array( 'jquery' ), 1.0, true );
$path = get_bloginfo( 'stylesheet_directory' );
// set the nonce security check
$ajax_nonce = wp_create_nonce( 'ajax_ac_nonce' );
wp_localize_script(
'ac-script',
'ac',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'path' => $path,
'security' => $ajax_nonce,
)
);
My question now becomes: How do I make the submitted comment data available to my PHP handler? I guessing I'll need to manually save the comment data to the database? I need this data available in my PHP function first but not sure how to do that?

Related

JavaScript with Ajax call to the WordPress API

I'm making a Wordpress plugin named "customposttype" that makes a custom post type with 3 custom fields. The plugin also must do an Ajax call to the WordPress API and gets all the data from those posts in JSON format, to show them in a specific template called "shoplist.php".
My CPT is called "tienda", it has this url for the REST API: ...wp-json/wp/v2/tiendas.
I'm sure that I have several errors because it's my first time using an API and I'm very bad at Javascript.
I'm stuck just right here, I don't know how to continue developing it.
JS shows "Hello world!" at the console, but nothing else.
PHP
add_action("wp_ajax_nopriv_get_shop_data", "get_shop_data");
add_action("wp_ajax_get_shop_data", "get_shop_data");
function get_shop_data() {
$api_url = "https://pezquefuma.es/wp-json/wp/v2/tiendas";
$request = wp_remote_get($api_url);
$body = wp_remote_retrieve_body($request);
$output = json_encode($body, true);
echo $output;
die();
}
function my_enqueue() {
if ( get_page_template_slug() == 'shoplist.php' ) {
wp_enqueue_script( 'ajax-script', plugins_url('customposttype/js/filename.js'), array('jquery') );
wp_localize_script( 'ajax-script', 'my_ajax_object', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('my-nonce')
)
);
}
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
JS
jQuery( document ).ready(function() {
console.log("Hello world!");
jQuery.ajax({
type : "GET",
dataType : "JSON",
url : my_ajax_object.ajax_url,
data : {
action: "get_shop_data",
},
error: function(response, error) {
console.log("wrong");
},
success : function(response) {
if(response.type === "success") {
console.log("Success");
}
}
});
});
There are two ways to check response data.
one is to use browser's network devtool and another is to use console.log
success : function(response) {
console.log(response);
}

Update post_author on button click via ajax request

I'm somewhat new to PHP and WordPress.
I'm attempting to update a posts "post_author" when a logged-in user, who is the author of this post, clicks on a button on the post page itself.
This is my code currently
PHP within functions.php file
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
$post = get_post($post_id);
if ($post->post_author == get_current_user_id()) {
wp_update_post(array(
'ID' => $post_id,
'post_author' => 1
));
}
wp_die();
}
Front end JS on the post itself
<script>
$(document).ready(function() {
$("#submit").click(function() {
var ajaxurl = 'MYDOMAINNAME/wp-admin/admin-ajax.php';
$.ajax ({
url: ajaxurl,
type: 'POST',
data: {
action: 'my_action',
id: 1234
},
})
});
});
</script>
<button id="submit">Change Author</button>
Ajax is quite new to me also so just trying to wrap my head around this and ensuring I'm approaching this the best way.
Use this code. You have use $_POST["id"] instead of $post_id.
footer.php
<script>
jQuery(document).ready(function() {
jQuery("#submit").click(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery.ajax ({
url: ajaxurl,
type: 'POST',
data: {
action: 'my_action',
id: 42
},
})
});
});
</script>
functions.php
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback($post) {
$post_id = $_POST["id"];
$post = get_post($post_id);
if ($post->post_author == get_current_user_id()) {
wp_update_post(array(
'ID' => $post_id,
'post_author' => 1
));
}
wp_die();
}
Update to my question, I was able to resolve the issue I was facing.
A couple of issues I was able to isolate were as follows.
I had a conflicting function that was triggering off of the save_post hook, which was causing the author to change back to the current user when triggering the wp_update_post() function. To resolve that I added a remove action before the function happens. See below.
remove_action('save_post', 'change_pos_auth');
remove_action('acf/save_post', 'change_pos_auth');
I used the following to get the ID of the current post when making an ajax request on that post page.
$url = wp_get_referer();
$post_id = url_to_postid( $url );

Can't Output Anything from WordPress AJAX, no Errors

I have an issue with Ajax in WordPress, I viewed 1000 posts about AJAX for a WordPress, but nothing. Everything seems ok.
I have a button with data-id attribute for every post on my index page, inside data-id I have its post id.
So idea is simple when someone click on this button I want to create a div with text, which will be post id. But I get nothing, I haven't any error, in my console everything is ok, but div is not created.
My enqueue scripts:
function _themename_assets() {
wp_enqueue_script( '_themename-dummy-scripts', get_template_directory_uri() . '/dist/assets/js/ajax.js', array('jquery'), '1.0.0', true );
wp_localize_script('_themename-dummy-scripts', 'viasun_dummy_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
));
}
add_action('wp_enqueue_scripts', '_themename_assets');
My JS:
$('.c-post__button a').on( 'click', function(e){
e.preventDefault();
var button = $(this);
var id = button.data('id');
var data = {
id: id,
action: "viasun_dummy_ajax_data_action"
};
$.ajax({
url: viasun_dummy_ajax.ajax_url,
data: data,
type: "POST",
beforeSend: function( ) {
console.log("sending");
},
success: function(message) {
if( data ) {
$("body").append(data);
console.log(data);
}
},
error: function() {
console.log("error");
}
} );
});
My action for ajax:
function viasun_dummy_ajax_data_action(){
$id = $_POST['id'];
echo '<div class="id-container">' . $id . '</div>';
wp_die();
}
add_action( 'wp_ajax_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
add_action( 'wp_ajax_nopriv_viasun_dummy_ajax_data_action', 'viasun_dummy_ajax_data_action' );
In my console from js I get:
Object { id: 15, action: "viasun_dummy_ajax_data_action" }
And XHR in console says 200 OK.
What am I doing wrong? Can you help me, please?

Wordpress jQuery send value to database

I am trying to send a value to my wordpress database (wp_usermeta table) when a button is clicked.
Here is what I know so far, I know I need to post the value using AJAX, I also know that wordpress has a function for updating the wp_usermeta table, that is:
update_user_meta( $user_id, 'dashboard_onboarding_status', 'myValue' );
The good news is that myValue isn't a variable - I just want to send the word "complete" to the db. It's also an admin side script - I'm not sure if that makes a difference on how to call the ajax url.
Here is what I have codewise:
In my main js file, I have the following AJAX script:
$('.skizzar_onabording_dashboard #next.step5').click(ajaxSubmit);
function ajaxSubmit(){
jQuery.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
"value" : "completed"
},
success:function(data){
console.log(data);
}
});
return false;
}
So when a user clicks on .skizzar_onabording_dashboard #next.step5 that should trigger the AJAX function.
Then in my main plugin php file I have the following:
function myFunction(){
global $wpdb;
$user_id = get_current_user_id();
$completed = $_POST['value'];
update_user_meta( $user_id, 'onboarding_status', $completed );
die();
}
add_action('wp_ajax_myFunction', 'myFunction');
I think needless to say this doesn't work, but I'm very new to using AJAX and I ca't figure out why. Seems like it should be simple though - essentially I just want to press a button and add "completed" to the key "onboarding_status" in the usermeta table.
Almost all you need is located here.
First you'll need to localize your admin-ajax.php, beause calling it like url: "/wp-admin/admin-ajax.php" is not a good practice.
wp_localize_script( 'some_handle', 'ajax_post_to_db', array(
'ajaxurl' => admin_url( 'admin-ajax.php'),
));
Then your ajax script to call:
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
global $wpdb;
$user_id = get_current_user_id();
$completed = $_POST['value'];
update_user_meta( $user_id, 'onboarding_status', $completed );
die();
}
And finally the ajax in your js file
$('.skizzar_onabording_dashboard #next.step5').on('click', function(){
ajaxSubmit();
});
function ajaxSubmit(){
jQuery.ajax({
type:'POST',
dataType: 'html',
url: ajax_post_to_db.ajaxurl,
data: {
action: 'my_action_callback'
},
success: function(data){
console.log(data);
},
error : function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR + ' :: ' + textStatus + ' :: ' + errorThrown);
},
});
return false;
}
This should be it.
DISCLAIMER
I'm never 100% sure if it's
data: {
action: 'my_action_callback'
},
or
data: {
'action': 'my_action_callback'
},
But try it and see which one will give you your function callback. I'm pretty sure it should be the first one.
Also you can check the return of the ajax call in your inspector. Just go to 'Network' tab and select XHR and you should see admin-ajax.php and when you click on it you can see all the relevant data it sends (headers, response etc.).
add your ajax function as the action
function ajaxSubmit(){
var data = {
'action': 'myFunction',
'value' : 'completed'
};
jQuery.post("/wp-admin/admin-ajax.php", data, function(response) {
console.log(response);
});
}

jQuery does not hit the Ajax URL on Wordpress

I am trying to implement a poll plugin on wordpress. The jQuery onchange event is working very fine of the below script but doesn't call or display the ajax hit on network .
plugin index page
PHP :
function my_scripts_main() {
wp_enqueue_script(
'my_voter_script',
plugins_url( '/js/main.js' , __FILE__ ),
array( 'jquery' )
);
wp_localize_script( 'my_voter_script',
'myAjax',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action'=>'my_poll_srt')
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_main' );
Plugin Short code Page :
add_action( 'wp_ajax_nopriv_my_poll_srt', 'my_poll_srt_callbck' );
add_action( 'wp_ajax_my_poll_srt', 'my_poll_srt_callbck' );
function my_poll_srt_callbck() {
global $wpdb;
$poll_id=$_POST['poll_id'];
$answer=$_POST['answer'];
$d=mktime(11, 14, 54, 8, 12, 2014);
$created= date("Y-m-d h:i:sa", $d);
/******* My Logic ****************/
echo json_encode(array('YES'=>$count_yes,
'NO'=>$count_no));
wp_die();
}
JS script :
jQuery(document).ready(function(){
jQuery("input[name=answer_srt]:radio").change(function (e) {
e.preventDefault();
// submit();
// $(this).closest("form").submit(function() {
// alert('Hello');
var poll_answer=$(this).val();
var poll_id=jQuery(this).closest("form").find('#poll_id_srt').val();
var vi=jQuery(this);
jQuery.ajax({
url: myAjax.ajaxurl,
type: 'POST',
data: {
action: myAjax.action,
answer:poll_answer,
poll_id:poll_id
},
// dataType: 'html',
success: function(response) {
var obj = JSON.parse(response);
// console.log(obj);
jQuery(vi).closest('form').find('#poll_sht').html('YES='+obj.YES+' NO='+obj.NO);
}
// });
});
});
});
In the code above there are no errors in console panel.
If I put alert() inside the script its working fine but its not hitting admin-ajax.php file. What to do now ? Where am I wrong please help me ?
Your action URL should contain query string of action.
e.g
The action URL is like this
http://localhost/wordpress/wp-admin/admin-ajax.php?action=my_poll_srt

Categories

Resources