Created
February 28, 2018 21:48
-
-
Save alexx855/1abe9aec15151c4f7c9f6008a2c2dfb6 to your computer and use it in GitHub Desktop.
Wordpress AJAX resquest example
This file contains hidden or 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 | |
add_action( 'wp_enqueue_scripts', function() { | |
// Register the script | |
wp_register_script('ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', ['jquery']); | |
// Localize the script with new data | |
wp_localize_script('ajax-script', 'my_ajax_object', ['ajax_url' => admin_url( 'admin-ajax.php' )]); | |
// Enqueued script with localized data. | |
wp_enqueue_script('ajax-script'); | |
}); | |
add_action( 'wp_ajax_my_custom_action', function() { | |
if ($_GET['data'] == 'val') { | |
wp_send_json_success(['message' => 'Success']); | |
} | |
wp_send_json_error(); | |
}); |
This file contains hidden or 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(function($){ | |
$.get(my_ajax_object.ajax_url, { 'action': 'my_custom_action', 'data': 'val' }, function (data) { | |
console.log(data); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment