1

I am trying to start a PHP function in Wordpress on the click of a link. I've managed to do it using a form-submit, but I want to do it on a link click.

I've pulled together an AJAX request but it doesn't seem to work - any thoughts much appreciated.

HTML Link Code

<a href="#link_id"> Ajax Click </a>

Javascript Function

<script>

// Create a function to pick up the link click

$('#link_id').click(function(event){
    event.preventDefault(); // prevent default behaviour of link click

    var data = {
        action: 'test_response_php', // This is the PHP function to call - note it must be hooked to AJAX
    };

    // Post to The Wordpress URL

    jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
        alert(response);
    });

});

PHP Function

function php_function() {
    echo 'Hello World';
    // Some interesting server side stuff

}

add_action('wp_ajax_nopriv_test_response_php', 'php_function');
add_action('wp_ajax_test_response_php', 'php_function');
8
  • 1
    change this <a href="#link_id"> Ajax Click </a> to <a id="#link_id" href = "#"> Ajax Click </a> #link_id should be an id not a href Commented Aug 2, 2017 at 18:25
  • Thanks Karthik. That doesn't seem to work either! Commented Aug 2, 2017 at 18:28
  • Any error in browser console when you clicked the link and jQuery starts running? Commented Aug 2, 2017 at 18:30
  • Any function that you're running from one of the wp_ajax_ hooks should end in an exit Commented Aug 3, 2017 at 2:02
  • Thanks @jakeparis That's super helpful to know. Is it just any function which is hooked wp-ajax OR also any function which is called in that function too? Commented Aug 3, 2017 at 14:57

1 Answer 1

4

Change your anchor tag like this:-

<a href="#" id="link_id"> Ajax Click </a>

You were missing id tag in anchor and you are running click event on id click.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.