Skip to content

Instantly share code, notes, and snippets.

@debabratakarfa
Created September 14, 2018 17:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debabratakarfa/ee4f12d93f9a6a980ff082442b793c69 to your computer and use it in GitHub Desktop.
Save debabratakarfa/ee4f12d93f9a6a980ff082442b793c69 to your computer and use it in GitHub Desktop.
AJAX Example
(function ($) {
$(document).ready(function () {
$('#test').click(function () {
$.ajaxSetup( { cache: false } );
$.ajax( {
type: 'POST',
dataType: 'json',
url: ajax.url,
data: {
action: 'test_wp_action',
function: link.data( 'sample-data' ),
nextNonce: ajax.formNonce
},
success: function ( response ) {
console.log(response);
//load the fetched php file into the div
$( '#div_id' ).html( response.content );
}
} );
return false;
});
});
})(jQuery);
add_action( 'wp_enqueue_scripts', 'custom_js_script' );
add_action( 'wp_ajax_test_wp_action', 'ajax_wp_action_func' );
add_action( 'wp_ajax_nopriv_test_wp_action', 'ajax_wp_action_func' );
function custom_js_script() {
wp_enqueue_script( 'inputtitle_submit', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ) );
wp_localize_script( 'inputtitle_submit', 'ajax', array(
'url' => admin_url( 'admin-ajax.php' ),
'nextNonce' => wp_create_nonce( 'sample-ajax-next-nonce' )
)
);
}
function ajax_wp_action_func() {
// check nonce
$nonce = $_POST['formNonce'];
if ( ! wp_verify_nonce( $nonce, 'sample-ajax-next-nonce' ) ) {
return;
}
$response = wp_send_json( $_POST );
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment