Created
November 24, 2018 00:06
-
-
Save williamsiuhang/e54a88584fb36e06c9cf9a18cbf5d102 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
// Fetches SQL table through ajax POST | |
// console.logs rows as JSON | |
// =============================== PHP (functions.php) | |
<?php | |
add_action( 'wp_ajax_clients', 'sql_get_clients' ); | |
add_action( 'wp_ajax_nopriv_clients', 'sql_get_clients' ); // postman (if user not logged in) | |
function sql_get_clients() { | |
global $wpdb; | |
$query = "SELECT * FROM table_name"; | |
$result = $wpdb -> get_results($query); | |
echo json_encode($result); | |
die(); | |
} | |
?> | |
// =============================== JS | |
async function sql_getclients() { | |
try{ | |
var url = ajaxurl; // | |
var data = new URLSearchParams(); | |
data.append('action', 'clients'); | |
var req = await fetch(url, { | |
method: 'POST', | |
headers: { "Content-Type": "application/x-www-form-urlencoded" }, | |
body: data | |
}); | |
var val = await req.text(); | |
var val_json = JSON.parse(val); | |
console.log(val_json); | |
}catch(e){ | |
console.log(e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment