EDIT: Complete re-write
I have been developing a custom extension for my theme over the last few weeks.
This is my first time "developing" with Wordpress. All works fine and I am happy with the resulting functionality, albeit it needs some tidying.
I wish to move my js functions out to an external file - custom.js.
Original format:
main-block.php
$custom1 = $custom_meta['custom1'];
<form name="customForm">
Validation Code:<br>
<!-- <input type="number" name="inputcode"><br> -->
<input type="password" name="inputcode" id="inputcode" maxlength="6" inputmode="numeric">
<input type="text" name="message" id="message" style="display:none; background-color: #FFCCCC;"><br>
<input type="button" name="submitbutton" value="Submit" onClick="customfunction()">
<div id="errors"></div>
</form>
<script type="text/javascript">
function customfunction() {
const userInput = document.customForm.inputcode.value;
const pidR = "<?php echo $postid ?>";
const useridR = "<?php echo $userid ?>";
fetch(`http://....../wp-json/api/v1/customquery?code=${userInput}&pid=${pidR}&userid=${useridR}`).then(r => r.json()).then(data => {
.....DO STUFF.....
})
};
</script>
I really dislike having this javascript declared inline.
I have tried so many things, with the added complication that my function uses variables pulled from the php:
const pidR = "<?php echo $postid ?>";
const useridR = "<?php echo $userid ?>";
const userInput = document.customForm.inputcode.value;
Currently in my child's functions.php I have written:
add_action('wp_head', function () {
// Register the script
wp_register_script( 'custom_script', get_stylesheet_directory_uri() . '/custom.js' );
// Localize the script with new data
$custom_api_vars = array(
'pid' => get_the_id(),
'uid' => get_current_user()
);
wp_localize_script( 'custom_script', 'custom_vars', $custom_api_vars );
// Enqueued script with localized data.
wp_enqueue_script( 'custom_script' , array('jquery'), '1.0', true);
});
and in my custom.js file:
function redeem() {
const pidR = custom_vars.pid;
const useridR = custom_vars.uid;
fetch(`http://....../wp-json/api/v1/customquery?code=${userInput}&pid=${pidR}&userid=${useridR}`).then(r => r.json()).then(data => {
.....do stuff.....
})
};
The API compares the value of inputcode from the form and performs an add/update_user_meta process based on whether inputcode matches a value in the database stored against the post.
When I call the function from my page I get this error in console:
Uncaught (in promise) ReferenceError: JQuery is not defined
I also need to know how I can externally call the other variable (below) as I don't think this would make sense within functions.php because it is related to the form on my page.
const userInput = document.customForm.inputcode.value;
I would be very grateful if someone could walk me through this.
Thank you if you got this far.