Reputation: 2616
My AJAX call returns 0.
Here is the jQuery.
$.ajax({
type: "POST",
url: ajaxurl,
data: {
action:"add_social_share_entry",
referral_code: "<?php echo Contest_Domination::get_referral_code("",""); ?>"
},
success: function(data){
alert(data);
}, error: function(error){
alert(error);
}
});
And the PHP.
function add_social_share_entry(){
$referral_code = $_REQUEST["referral_code"];
if ( class_exists( 'Contest_Domination' ) ) {
if (!empty($referral_code)) {
$referral_submission = Contest_Domination::get_submission_by_referral_code($referral_code);
if($referral_submission!==false){
$referral_id = $referral_submission->submission_ID;
Contest_Domination::add_entries($referral_id, 1);
echo "Successfully added entry";
}
}else{
echo "Referral code not received";
}
}else{
echo "Class does not exist";
}
die();
}
add_action('wp_ajax_add_social_share_entry', 'add_social_share_entry');
add_action('wp_ajax_nopriv_add_social_share_entry', 'add_social_share_entry');
These are both on the same page (a template page), and the response is 0. Let me know if you need additional information or request headers. This is stupefying me. Thanks!
EDIT: I realized I might have been a bit ambiguous. The JS and PHP are both in a PHP template file, so the PHP bit runs fine. I'll show my headers so it isn't thought that the error is coming from there.
action:add_social_share_entry
referral_code:552ec562300af
SOLUTION
As Lukas pointed out below, I needed to move the WP AJAX hooks into my functions.php
file in my theme because it wasn't working within my plugin.
Upvotes: 1
Views: 126
Reputation: 146
Could you try moving your PHP part
function add_social_share_entry() {
.....
}
add_action('wp_ajax_add_social_share_entry', 'add_social_share_entry');
add_action('wp_ajax_nopriv_add_social_share_entry', 'add_social_share_entry');
to your WordPress functions.php theme file? I guess WordPress doesn't register that hooks if you have placed them in template.
Upvotes: 1
Reputation: 21759
The problem here is that you are mixing javascript with php in the wrong way, first:
referral_code: "<?php echo Contest_Domination::get_referral_code("",""); ?>"
That will never work, unless you are rendering your javascript file via PHP, which i suppose you dont.
Having this on hand, you can tell where your code is ending:
die();
You are sending nothing back to your jquery success/errro callbacks.
I recommend you check on how you are getting the referral code, and once you've got it and send it to your PHP, use some headers with status code and response text so you can tell your jquery ajax when it should call error and when it should call success.
Try removing the die();
from your function, that is killing the script execution and might be the cause of the problem.
Upvotes: 0