AJAX function not working when placed inside a plugin

I have a simple AJAX function that I’ve placed inside my theme’s functions.php. It works, and “working” is returned correctly to the jQuery ajax request, so that side of things is fine.

BUT, when the same function is placed into a plugin instead, it no longer works, just returns 0.

Read More
function addCustomer(){

    echo "working";
    die();

}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');

I also tried placing the action hook inside an
if ( is_admin() )
as was suggested in this tutorial, but no luck.

I think I’m probably overlooking something incredibly obvious, but I can’t figure it out. Any help appreciated, because I’ve been googling for hours now.

EDIT: Here’s the AJAX call I’m using:

<script type="text/javascript">
                        jQuery('#newCustomerForm').submit(ajaxSubmit); 

                        function ajaxSubmit(){

                            var newCustomerForm = jQuery(this).serialize();

                            jQuery.ajax({
                                type:"POST",
                                url: "/wp-admin/admin-ajax.php",
                                data: newCustomerForm,
                                success:function(data){
                                    jQuery("#feedback").html(data);
                                },
                                error: function(errorThrown){
                                    alert(errorThrown);
                                }   
                            });

                            return false;
                        }

but I’m certain this bit is fine, as it’s working perfectly when the receiving function is placed in functions.php, just not when placed in a separate plugin.

Related posts

Leave a Reply

2 comments

  1. I had the same problem too but when running in debug (firebug) I got a 404 error, the url: “/wp-admin/admin-ajax.php” was missing. To fix this change it to url section as below:

    function ajaxSubmit(){
     var newCustomerForm = jQuery(this).serialize();
     jQuery.ajax({
      type:"POST",
      url: "<?php echo home_url('/'); ?>/wp-admin/admin-ajax.php",
      data: newCustomerForm,
      success:function(data){
       jQuery("#feedback").html(data);
      },
      error: function(errorThrown){
       alert(errorThrown);
      }   
     });
     return false;
    }
    

    and it should work

    VK

  2. I also had the similar issue. The Ajax function was working when placed in function.php and not when inside a plugin.

    Turns out it was because of W3 Total Cache, after purging all cache solved the issue.