skip to Main Content

I’m in the process of creating a very simple ajax function, but unfortunately it does not enter the ajax handler function. I’m wondering what is wrong with this code?

Function in functions.php:

function set_favourite_order() {
 
    update_user_meta( 1, 'favorder', 'enterajax' );
   
    // Always die in functions echoing ajax content
   die();
}
 
add_action( 'wp_ajax_set_favourite_order', 'set_favourite_order' );
add_action( 'wp_ajax_nopriv_set_favourite_order', 'set_favourite_order' );

Javascript:

jQuery(document).ready(function($){
                    $.ajax({
                    type: 'POST',
                    url: ajaxurl,
                    data: {
                        "action": 'set_favourite_order',
                        "favourite_order" : "test",
                        "pet_id": 8436
                    },
                    success:function(data) {
                        // This outputs the result of the ajax request
                        console.log('success');
                    },
                    error: function(errorThrown){
                        console.log(errorThrown);
                    }
                });  
 } );

The ajaxurl in the javascript is the link to /wp-admin/admin-ajax.php and running it results in a success message every time.

The problem is that the ajax handler does not run. Any idea what’s wrong? I’ve been trying to debug this for a day.

2

Answers


  1. Please return JSON object in your ajax callback function and use dataType : JSON

    function set_favourite_order() {
       update_user_meta( 1, 'favorder', 'enterajax' );
    
       // Add this line
       echo json_encode(array('result'=>'Success Message'));
       die();
    }
    

    In you Js file add dataType.

    $.ajax({
        dataType: "JSON", // and all your args
    },
    success:function(data) {
    // This outputs the result of the ajax request
    console.log(data.result); // Out should be "Success Message"
    });
    
    Login or Signup to reply.
  2. Always remember that ajaxurl is a variable that stores the admin-ajax.php path and by default wordpress does not provide admin-ajax.php onto the frontend. So you need to initialize it first. There are various way to use, one popurar way is to localize the js.

    Here is an another shortest way

    <script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search