A little rant before the code
Javascript is language, jQuery is a library programmed in that language. It’s like “English” and a “book written in English”.
As the world is moving towards Core/Vanilla Javascript after release of ES6 update from ECMA. jQuery is a time bomb in the world of WordPress. With Gutenberg integrated, WordPress have included itself into the world of React and ES6. Soon, there might come a day where WordPress might no longer include jQuery in its core.
To give some love towards jQuery, it is so robust that it is still powering major share of the world websites. It is the web technology that has evolved to a point where we need to move on from good old jQuery.
Objective : Get user object when a user is selected in a dropdown
The select dropdown with current WP users is as follows.
<?php
$users = get_users(); // Get all users in WordPress
if($users){ // Check if users array is not empty
?>
<select id="sleek-user">
<option value="">-Select-</option>
<?php
foreach($users as $user){ // Loop through users
?>
<option value="<?php echo $user->ID; ?>"><?php echo $user->display_name; ?></option>
<?php
}
?>
</select>
<div id="sleek-user-details"><!--Show ajax response here--></div>
<?php
}
?>
The above code will generate a HTML as follows
<select id="sleek-user">
<option value="">-Select-</option>
<option value="1">John Doe</option>
<option value="8">Jane Doe</option>
<option value="11">Jim Hopper</option>
<option value="12">Mike Cook</option>
<option value="14">Janet Russell</option>
</select>
<div id="sleek-user-details"><!--Show ajax response here--></div>
Handle ‘onchange’ event in Javascript for the above created users dropdown
// If sleek-user id element exists
if( document.getElementById('sleek-user') ){
// Get the element
var element = document.getElementById('sleek-user');
// Handle the selected/changed event
element.addEventListener('change', (event) => {
// Do the Ajax call here
});
}
Prepare parameters for the ajax call.
const params = new URLSearchParams(); // Initiate params variable
params.append('user_id', element.value); // selected user id
params.append('action', 'sleek_get_user_details'); // Ajax function to be called
Make the ajax call
// Make the ajax call
// In the place of ajaxurl use the wp ajax URL (/wp-admin/admin-ajax.php)
fetch(ajaxurl, {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache',
},
body: params,
})
PHP Ajax function that handles the ajax request is as follows
<?php
// Function to handle the ajax request
function sleek_get_user_details(){
$user_id = $_REQUEST['user_id']; // Get user_id from parameters
$user = get_user_by('id', $user_id); // Get user by id
?>
<div>First name : <?php echo $user->first_name; ?></div>
<div>Last name : <?php echo $user->last_name; ?></div>
<div>Email : <?php echo $user->user_email; ?></div>
<div>Login : <?php echo $user->user_login; ?></div>
<?php
exit;
}
// Hook to register the ajax function in WordPress
add_action('wp_ajax_sleek_get_user_details', 'sleek_get_user_details');
?>
Handle the ajax response from server in Javascript
.then(response => {
return response.text(); // Convert the response as text
})
.then( html => {
// Update the user details in the response div
document.getElementById('sleek-user-details').innerHTML = html;
})
.catch(err => console.log(err)); // Log error in console if any
Putting it all together
// If sleek-user id element exists
if( document.getElementById('sleek-user') ){
// Get the element
var element = document.getElementById('sleek-user');
// Handle the selected/changed event
element.addEventListener('change', (event) => {
if(element.value != ''){ // Check if selected option has a value
const params = new URLSearchParams(); // Initiate params variable
params.append('user_id', element.value); // selected user id
params.append('action', 'sleek_get_user_details'); // Ajax function to be called
// Make the ajax call
// In the place of ajaxurl use the wp ajax URL (/wp-admin/admin-ajax.php)
fetch('/jitsi/wp-admin/admin-ajax.php', {
method: 'POST',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cache-Control': 'no-cache',
},
body: params,
})
.then(response => {
return response.text(); // Convert the response as text
})
.then( html => {
// Update the user details in the response div
document.getElementById('sleek-user-details').innerHTML = html;
})
.catch(err => console.log(err)); // Log error in console if any
}
else{
// Update the response div with empty text
document.getElementById('sleek-user-details').innerHTML = '';
}
});
}
Conclusion
There is always a cost when using a library or framework. We’re giving away some performance for faster and easier development. Is the performance gap significant though? In most use cases, no. In fact, users won’t even notice the difference. Does that mean we are good to use jQuery? No.
Back in the day, it was hard writing JavaScript code which would be fully supported in all browsers. That’s where jQuery came into play. Today, however, most of those problems do not exist any more. Pulling in jQuery just for DOM manipulation is not worth it.