I'm new to nuBuilder and I'm getting accustomed to the architecture and php in general. I'm trying to create an autofill function in the custom code to take a user name selected from a dropdown menu, find that user in the db, and autofill other fields associated with the user (e.g. name and email) from the information retrieved from the db. I'm wondering if there is built-in or simpler way to achieve this than how I'm approaching this problem. Below is my code. I have a variable named nameDropdown because I was expecting to be able to capture the name through the dropdown select input, but the value stored in nameDropdown is actually a string representation of a subform obj. I'm at a loss how to implement the right combination of js, jquery, and php to make my function work. Any help would be greatly appreciated!
function autoFillForm() {
//Get string representation of subform_participants object
const nameDropdown = nuGetValue('subform_participants', 'text');
console.log(nameDropdown)
// Get the selected name from the dropdown
const selectedName = nameDropdown.value;
// Split the selected name into 'firstName' and 'lastName'
const nameParts = selectedName.split(' ');
const firstName = nameParts[0];
const lastName = nameParts.length > 1 ? nameParts.slice(1).join(' ') : '';
// Make an AJAX request to the PHP script
$.ajax({
type: 'POST',
url: 'script.php', // Replace with the actual path to PHP script
data: { first_name: firstName, last_name: lastName },
dataType: 'json',
success: function(response) {
// Check for errors in the response
if ('error' in response) {
console.error(response.error);
return;
}
// Assume you have form fields with IDs 'email' and 'phone'
$('#email').val(response.email);
$('#phone').val(response.phone);
},
error: function(error) {
// Handle errors
console.error(error);
}
});
}
Thanks for your help, Steven! This definitely looks like the direction I need to go and I'm playing around with it.
I do have some followup questions:
1. Is it possible to set this code up for a subform or is it only capable for forms?
2. Is it possible to create this setup with a dropdown instead of a text field?
Thank you! Your original advice did the trick! I just had to dig through the forms a little and figure out what tables they were tied to in the database (I didn't create the project myself).