I have a problem with AJAX returning 0 always!
I have done everything by the book and can’t figure out what is wrong? Please help!!
Here is my Ajax call:
//Pass data through AJAX
var amountToConvert = price;
jQuery.ajax({
type:"POST",
url: "../../wp-admin/admin-ajax.php", // our PHP handler file
action: "ajaxConversion",
data: {
amount: amountToConvert
},
success:function(data){
alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});
return false;
And the function in functions.php is:
function ajaxConversion(){
$amount = mysql_real_escape_string($_POST['amount']);
echo $amount;
die();
};
add_action('wp_ajax_nopriv_ajaxConversion', 'ajaxConversion');
add_action('wp_ajax_ajaxConversion', 'ajaxConversion');
Could you place the action (ajaxConversion) in your Data and check?
using
wp_die();
at the end of AJAX function fixed the issue for me.e.g
For me the trick was to add
wp_ajax_nopriv
action. I tested the script on one browser when I was logged in WP admin, and then I tried same script in Chrome and realized that the script doesn’t work. After I putwp_ajax_nopriv
, everything started to work. 🙂I would recommend using wp_send_json_success() and wp_send_json_error() on server side.
You don’t need to worry about die() etc and the “status” variable is sent automatically, it’s much cleaner this way. For example
Will result in something like this:
So then you can do easily extract the values in your ajax call:
Another common thing i’ve ran into are typos in the action name. They should be wp_ajax_nopriv_{action} or
wp_ajax_{action} when logged in. For example, wp-ajax_nopriv, is one I’ve done several times in the past.
For me it was the fact that I was using
return
instead ofecho
in my PHP function. Changing it toecho
fixed it.You may forget to add below line:
add_action("wp_ajax_your_ajax_function", "your_ajax_function");
Without above line, the ajax it not be fired.
Here is your ajax function
function your_ajax_function(){ $result = json_encode($result); echo $result; }