Created
September 14, 2018 17:08
-
-
Save debabratakarfa/ee4f12d93f9a6a980ff082442b793c69 to your computer and use it in GitHub Desktop.
AJAX Example
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 ($) { | |
$(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); |
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
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