js file: (walking_log.js)
jQuery.ajax
({
url: '<?php echo admin_url("admin-ajax.php"); ?>',
type: 'POST',
data: {
'action':'myaction'
},
success: function(data)
{
alert('Happy new year 2015 :) ');
},
error: function(data)
{
alert( 'Sorry! No Happy New year 2015 :(' );
}
});
php file:
// Ajax Handler.
function so_enqueue_scripts()
{
$plugin_dir_path = dirname(__FILE__);
$plugin_url = plugins_url();
wp_enqueue_script( 'ajaxHandle', $plugin_url . '/walking-log/js/walking_log.js', array('jQuery') );
wp_localize_script( 'ajaxHandle', 'myAjax', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
}
add_action( 'init', 'so_enqueue_scripts' );
function so_wp_ajax_function()
{
die();
}
path of walking_log.js is right, i have opened it in the browser. I am getting the success failure alert. don't know why. any help would be appreciated.
Edit:
I am getting this on firebug.
"NetworkError: 404 Not Found - http://192.168.1.6/Interaction/exercise-log/%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E"
why this is happening?
In js file, This line must be causing the error..
url: '<?php echo admin_url("admin-ajax.php"); ?>',
You are calling a php function admin_url in js file. JS files will not call your php fn.
Your error confirms it .... Encoded url
%3C?php%20echo%20admin_url(%22admin-ajax.php%22);%20?%3E
Decoded URL
<?php echo admin_url("admin-ajax.php"); ?>
Related
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 );
I just started experimenting with jQuery and ajax. I have looked through similar posts but I am still unable to resolve my issue.
So here goes, I am writing a wordpress plugin. I have the following:
add_action('wp', 'wl_init');
add_action('wp_ajax_wl_add_wishlist', 'wl_wishlist_process');
add_action('wp_ajax_nopriv_wl_add_wishlist', 'wl_wishlist_process');
function wl_wishlist_process (){
echo 'test';
die();
}
function wl_init(){
wp_register_script( 'wishlist-js', plugins_url( '/wishlist.js', __FILE__ ), array('jquery') );
wp_localize_script( 'wishlist-js', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery');
wp_enqueue_script( 'wishlist-js' );
}
And this is my js file"
jQuery(document).ready(function($) {
$('#wl_wishlist').click(function(e) {
alert('This runs');
//var plugurl = document.location.protocol+'//'+document.location.host+'/test/wp-admin/admin-ajax.php';
//"<?php echo admin_url('admin-ajax.php'); ?>"
//"/test/wp-admin/admin-ajax.php"
jQuery.ajax({url: myAjax.ajaxurl, type: 'post', data: {action: 'wl_wishlist_process', post_id:100}, success: function(response) {
alert(response);
},
error : function (xhr){
alert('There is an error');
}});
});
});
I know the js file is loaded and running as I see the alert('This runs'). However, it neither gives me success nor error. Is it error with the ajax call or is it the callback function error? What am I missing here?
Also, When I open the url of the ajax call (http://localhost/test/wp-admin/admin-ajax.php), it shows '0'. Is this correct?
I have used all the commented methods to get the url, but none works.
Thanks!
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
I can't figure out why nothing is returned
I am a real beginner in Ajax ..
I just read a lot of topics about using Ajax in Woprdpress but the examples are super advanced for me
Here is my JS code combo_checkout_iRange.js
jQuery(document).ready(function() {
jQuery('#loader').hide();
jQuery('#check-out-date').hide();
jQuery('#check-in-date').change(function(){
jQuery('#check-out-date').fadeOut();
jQuery('#loader').show();
jQuery.ajax({
type: 'POST',
url:myAjax.ajaxurl,
data: {
action : 'my_ajax_handler',
parent_id: jQuery("#check-in-date").val()
},
success: function(data){
alert(data);
jQuery('#loader').hide();
jQuery('#check-out-date').show();
jQuery('#check-out-date').append(data);
}});
return false;
});
jQuery('#check-out-date').change(function(){
alert(jQuery('#check-out-date').val());
});
});
This is what I wrote on function.php
Note: this should work in post type called "meetings"
add_action("wp_enqueue_scripts", function() {
if (is_single()) {
if (get_post_type() == 'meetings')
{
wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true);
$data_array = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_register_script( 'combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array('jquery') );
wp_localize_script( 'combo_checkout_iRange', 'myAjax', $data_array );
}
}
});
and this is my ajax handler i put it inside single_meetings.php
add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");
function my_ajax_handler() {
if ( isset($_REQUEST["parent_id"]) ) {
$id = $_REQUEST["parent_id"];
return $id;
die();
}
}
You can't use return in your AJAX callback. The code never gets to die on the line beneath. You need to echo the value instead and then use wp_die().
Replace:
return $id;
die();
With:
echo $id;
wp_die();
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?