[Vuejs]-WordPress – send ajax request from vuejs app

1👍

wp_localize_script function is often used to pass generic data from PHP to JavaScript.

In simple words, if you have to pass some data from php to Javascript, WordPress later add a new function wp_add_inline_script but wp_localize_script is better when you’re registering a script.

This function needs 3 args:

  1. handle name – that is your registered script name.
  2. js object name – an object name that you can use globally in your Js file
  3. data array – a php array of data, you don’t need to json encode it, wordpress will do it for you.
function setup_ajax_vue() {
    wp_register_script( 'vue-css', get_template_directory_uri() . '/dist/assets/index.css' );
    wp_enqueue_style( 'vue-css' );

    wp_register_script( 'vue-js', get_template_directory_uri() . '/dist/assets/index.js', array(), false, true );
    wp_enqueue_script( 'vue-js' );
    wp_localize_script( 'vue-js', 'vue_js_params', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'setup_ajax_vue' );

so in your code, you’ll localize the php data with your registered script by the above code.

Note: you need to register the script first and then localize it.

in the above code, we have used the js object name vue_js_params and we’ve passed ajaxurl in the data.

so in your js code, you can access it using vue_js_params.ajaxurl it will be globally available to be used.

If you don’t know how to register an ajax callback in WordPress then you can learn it from tutorials, I am sure there will many google article on "How to use ajax in WordPress"

1👍

Added somewhere in your page this code before your ajax call.

<script>
    var ajax_url= "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

So then you can:

    <center>
        <button style="margin:50px" onclick="do_ajax()">Ajax</button>
    </center>

    <script>
        var url = "<?php echo admin_url('admin-ajax.php'); ?>";
        function do_ajax() {
            var request = new XMLHttpRequest();
            request.open("POST", url + "?action=process_contact_form");
            request.onreadystatechange = function() {
                if(this.readyState === 4 && this.status === 200) {
                    alert(this.responseText);
                }
            };
            var formData = new FormData();
            formData.append("subject", "value");
            formData.append("message", "hello value")
            request.send(formData);
        }   
    </script>

Or of course using axios or fetch.

Leave a comment