Instantly share code, notes, and snippets.

Embed
What would you like to do?
//prepare javascript
function ajax_enqueue()
{
wp_enqueue_script( 'my-script',get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
wp_localize_script( 'my-script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('wp_enqueue_scripts', 'ajax_enqueue');
//to enable ajax call on jquery
function ajax_sample()
{
$sample_ajax = $_POST['hello'];
echo $sample_ajax;
wp_die();
}
add_action('wp_ajax_ajax_sample','ajax_sample');
add_action('wp_ajax_nopriv_ajax_sample','ajax_sample');
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
'use strict';
$(".btn_submit").click(function(e){
e.preventDefault();
var hello = $('.txt_input').val();
$.ajax({
type:"POST",
data:{
action:'ajax_sample',
hello:hello,
},
url : myAjax.ajaxurl,
success:function(data)
{
alert(data);
}
})
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment