jquery - Theme customisation - how to store javascript externally when it utilises php variables?

EDIT: Complete re-writeI have been developing a custom extension for my theme over the last few weeks.This is my first t

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.

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.

Share Improve this question edited Jul 21, 2019 at 0:26 fuxia 107k39 gold badges255 silver badges459 bronze badges asked Jul 20, 2019 at 10:59 Shaun21ukShaun21uk 311 silver badge8 bronze badges 2
  • 1 Please only ask one question at a time. – Jacob Peattie Commented Jul 20, 2019 at 11:08
  • Ok, tried my best to re-write this. – Shaun21uk Commented Jul 20, 2019 at 12:10
Add a comment  | 

1 Answer 1

Reset to default 0

Since it's a plugin, you should enqueue jQuery first.
Inside your add_action('wp_head', function () { before wp_register_script( 'custom_script', get_stylesheet_directory_uri() . '/custom.js' ); add :

if ( ! wp_script_is( 'jquery', 'enqueued' )) {
    //Enqueue jQuery
    wp_enqueue_script( 'jquery' );
}

This will check if jQuery is loaded and if not it will load it.

Then, in your custom.js file put the following :

(function ($) {
    const pidR = custom_vars.pid;
    const useridR = custom_vars.uid;
    // do stuff...
})(jQuery);

Hope this will help you get on the track ;)

SYA :)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745308467a4621857.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信