1

I have checked so many links but i didn't succeeded using ajax in wordpress.

Foooter.php

<script type="text/javascript">
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

custom.js

jQuery('#elementid').on('keyup', jqueryfunction);

function jqueryfunction(id) {
    var value = jQuery(this).val();
    if (value.length > 3) {
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: 'value=' + value,
            success: function (data) {
                console.log(data);
            }
        });
    } else {
        $('.showcount').remove();
    }
}

functions.php // I think i am wrong here. I don't know where to write this code

wp_enqueue_script('jquery');
function mycustomfunction() {
    echo "Function found";
}

add_action('wp_ajax_mycustomfunction', 'mycustomfunction');
add_action('wp_ajax_nopriv_mycustomfunction', 'mycustomfunction');

In the console it only shows 0 but it should show Function found. Can someone please refer me where to write this code so that it will work.

1

In above case your ajax request is not reaching your php function, thus it founds nothing. Update your jquery function with this

 function jqueryfunction(id) {
    var value = jQuery(this).val();
    if (value.length > 3) {
        jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'mycustomfunction',
                value: value,
                },
            success: function (data) {
                console.log(data);
            }
        });
    } else {
        $('.showcount').remove();
    }
}

as you can see that i added a parameter "action" which is name of your ajax request after wp_ajax_.

Also update your php function with

function mycustomfunction() {
    echo "Function found";
die; //wp_die();
}

Add die at end of your function , otherwise you will see a "0" with your ajax response.

Hope it will help you.

  • I am glad it helped you @Tuku – Harry Mar 29 '17 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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