I am developing a plugin called my-search-site and in that I have site links. If I click on the link, the jQuery function is called and that jQuery variable is passed to wordpress function from which It can be added to user meta.

My jQuery looks like this:


        //toggle between the star icon 
        $(this).toggleClass('star-empty star_filled');
        //retrieve the clicked link's ID and it's href
        var fav_id =  $(this).parent().parent().attr('id');
        fav = $(this).parent().parent();
        //append favorites using ajax call

                url: ajaxurl + "?action=fdiAddFavorite",
                data: {
                        action: 'fdiAddFavorite',
                        fav_id: fav_id,

                error: function(errorThrown){

        //}).always(function() { alert("complete");

        return false;

and on the same page my wordpress function is declared as below:

 add_action('wp_ajax_fdiAddFavorite', 'fdiAddFavorite');
 add_action('wp_ajax_nopriv_fdiAddFavorite', 'fdiAddFavorite');

 function fdiAddFavorite() {
    $fav_id = get_post($_REQUEST['fav_id']);
    $user_id = get_current_user_id();
    $favorite_list = get_user_meta($user_id, 'favorite links', true);
        $favorite_list = array();

    $favorite_list[] = $fav_id;
    update_user_meta($user_id, 'favorite links', $favorite_list);
    die('{"success": true}');

After click event the ajax returns 0 and the function is not called and can not be recognized by ajax call. I am not able to update the user meta. Can you please help me with it. Thanks

  • 1
    What do you mean by your Ajax function being "on the same page"? What file do you declare that in? Remember that Ajax requests are a separate http request from the page you are making the requests from.
    – Milo
    Commented Apr 5, 2017 at 21:58
  • the ajax query and the function which is called by ajax are on the same page. I haven't make two different files for that. Commented Apr 5, 2017 at 23:11
  • How are you adding the javascript to your file? Commented Apr 5, 2017 at 23:48
  • Your Ajax function won't be loaded on the Ajax request because that is a different page- your Ajax function should be in a file that is loaded on all requests.
    – Milo
    Commented Apr 6, 2017 at 11:55

1 Answer 1


Instead of url: ajaxurl + "?action=fdiAddFavorite",, use two lines like this:

url: ajaxurl,
action: "fdiAddFavorite",

Then at the end of fdiAddFavorite(), you try something like this:

echo $favorite_list; // could also send message like "success!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.