0

I want after click button run function, . All is in one class.

JQUERY

jQuery('#text2').click(function() {

    var data = {
        'action': 'myfunction',
        'whatever': $button.data('text2'), 
    };   

    // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
    jQuery.post(ajaxurl, data, function(response) {
        alert('Got this from the server: ' + response);
    });
});

PHP

      public function myfunction() {

       $write = intval( $_POST['whatever'] );

       $write++;

       echo $write;
       wp_die();

      } 

HTML

<button id="text2" value="1500"> test </button>
1

In order to make this work as you expect, you need to add the following lines in your constructor (depending on the requirements you have)

add_action( 'wp_ajax_myfunction', array($this, 'myfunction') );
add_action( 'wp_ajax_nopriv_myfunction', array($this, 'myfunction') );

Note that wp_ajax_nopriv_myfunction executes for users that are not logged in. The other executes for logged in users only.

You also need to just check that in your JS, ajaxurl returns your ajax URL.

If not, you'll need to expose that URL for usage in your JS. You can do that by following the codex here: https://codex.wordpress.org/Function_Reference/wp_localize_script

You will need to call wp_die(); at the end of your PHP function as well.

  • Constructors are a bad place for adding actions, see this answer. – kero Jun 5 at 14:16
  • @kero That answer was in regards to instantiating a class via a hook. In the example above, we are calling the hook within the class as given in the first example of the above answer you referred us to. – Steve North Jun 5 at 14:49
  • When i write data and have many the same buttons, if I click one, then other not work, probably by wp_die(). How solve this? – polyman Jun 6 at 15:30
  • @polyman Unsure what you mean I'm afraid. Can you give an example? – Steve North Jun 11 at 9:41

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.