Created
May 7, 2014 12:15
-
-
Save tormjens/427fc1c19550c0f98df0 to your computer and use it in GitHub Desktop.
WP Ajax
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
jQuery(document).ready(function($) { | |
var data = { | |
action: 'smart_ajax', // the action as defined on line 8 of the PHP file | |
myVar: 'Hello World' // will be sent to the php within the $_POST global | |
}; | |
$.post(SmartAjax.ajax, data, function(response) { | |
console.log(response); | |
}); | |
}); |
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 smn_ajax() { | |
echo $_POST['myVar']; | |
die(); // die at end to return proper results | |
} | |
add_action( 'wp_ajax_smart_ajax', 'smart_ajax' ); // for logged in users | |
add_action( 'wp_ajax_nopriv_smart_ajax', 'smart_ajax' ); // for non-logged in users | |
// enqueue script and localize it to get the admin ajax | |
function smart_scripts() { | |
wp_enqueue_script('ajax-script', get_template_directory_uri() . '/js/ajax.js', array('jquery'), false, true); | |
wp_localize_script( 'custom-script', 'SmartAjax', array('ajax' => admin_url('admin-ajax.php')) ); | |
} | |
add_action( 'wp_enqueue_scripts', 'smart_scripts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment