Last active
September 10, 2019 14:01
-
-
Save wolffe/fcba31a1ca34fd312f864f3f7a128b5e to your computer and use it in GitHub Desktop.
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
<?php | |
function my_plugin_enqueue_scripts() { | |
wp_enqueue_script('my-plugin', plugins_url('/assets/js/init.js', __FILE__), [], '', true); | |
wp_localize_script('my-plugin', 'myAjaxVar', [ | |
'ajaxurl' => admin_url('admin-ajax.php'), | |
'url' => 'https://ckp.ie' | |
]); | |
} | |
add_action('wp_enqueue_scripts', 'my_plugin_enqueue_scripts'); | |
function save_to_database() { | |
$array = $_POST['array']; | |
// Do stuff | |
wp_die(); | |
} | |
add_action('wp_ajax_save_to_database', 'save_to_database'); | |
add_action('wp_ajax_nopriv_save_to_database', 'save_to_database'); | |
// Javascript | |
function apiPostXhr(url, action, data) { | |
var request = new XMLHttpRequest(); | |
request.open('POST', url, true); | |
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); | |
request.onload = function (response) { | |
if (this.status >= 200 && this.status < 400) { | |
// Response success | |
} else { | |
// Response error | |
} | |
}; | |
request.onerror = function() { | |
// Connection error | |
}; | |
request.send('action=' + action + data); | |
} | |
// Call the function | |
apiPostXhr(myAjaxVar.ajaxurl, 'save_to_database', '&array=' + myArray); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment