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>
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>
Share
Improve this question
edited Jul 21, 2019 at 23:13
Jaron
asked Jun 5, 2019 at 11:53
JaronJaron
458 bronze badges
1
- 1 This is not how AJAX requests in WordPress work. Check out the Plugin Handbook on AJAX - or even better the REST API Handbook. – kero Commented Jun 5, 2019 at 12:25
1 Answer
Reset to default 1In 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/Function_Reference/wp_localize_script
You will need to call wp_die();
at the end of your PHP function as well.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745307521a4621803.html
评论列表(0条)