Last active
April 6, 2018 09:47
-
-
Save andreilupu/26ac093c885aa0b8d9f25dd0271f1726 to your computer and use it in GitHub Desktop.
How to send a POST request from WordPress admin Dashboard
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var request = wp.ajax.post('custom_action', {param1: 'uppercase this string pls'}); | |
// on success | |
request.done( function ( res ) { | |
console.log( res ); | |
}); | |
// on fail | |
request.fail( function ( res ) { | |
console.log( res ); | |
}); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// this function will be called when the request is triggered | |
function listen_for_ajax() { | |
if ( ! empty( $_POST['param1'] ) ) { | |
$upercased = strtoupper( $_POST['param1']); | |
wp_send_json_success( $upercased ); | |
} | |
wp_send_json_error('no param'); | |
} | |
// hook this function for admin actions | |
add_action( "wp_ajax_custom_action", "listen_for_ajax"); | |
// for public actions use `nopriv_` before action name | |
add_action( "wp_ajax_nopriv_custom_action", "listen_for_ajax"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment