I have a contact form in a WordPress page like this:

$( '#contact_form' ).bootstrapValidator({
    fields: {
        // ...
    },
    submitHandler: function( formInstance ) {
        $.post( "../send-message", $("#contact_form").serialize(), function( result ) { 
            alert( pw_script_vars.State );            
        });
    }
}); 

When the form is submitted using the Ajax request it goes to another WordPress page titled /send-message that has PHP code to send an email, then it should return a success or failure value to the Ajax request to alert a success or failure message. I have tried using the wp_localize_script function in the functions.php file using a fixed value and it worked fine:

function enqueue_scripts() {
    wp_enqueue_script( 'pw_script', get_stylesheet_directory_uri().'/inc/js/functions.min.js', array( 'jquery' ) );
    wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

But when I tried to use the wp_localize_script in the /send-message WordPress page it failed to work. Here are the contents of the ‘/send-message’ page :

<?php
    $sendSuccess = sendMessage();

    if( $sendSuccess )
        wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'success' ) );
    else
        wp_localize_script( 'pw_script', 'pw_script_vars', array( 'State' => 'failure' ) );

    function sendMessage() {
        //This function will send the email then it will return true or false.
    }
?>

Using wp_localize_script in the /send-message causes an undefined variable pw_script_vars in the JavaScript file.

How can I use wp_localize_script in a WordPress page other than functions.php?

2 Answers
2

You cannot use wp_localize_script in page template. You have to use it in functions.php or your custom plugin, after you register your script, which is usually in the wp_enqueue_scripts action.

https://codex.wordpress.org/Function_Reference/wp_localize_script

Leave a Reply

Your email address will not be published. Required fields are marked *