简体   繁体   中英

Call function javascript from PHP

---- avarias_js.js ----

function limpar() { alert('test'); }

---- avarias.php ----

add_action('init','initjs');

function initjs() {

    wp_enqueue_script( 'avarias_js', plugins_url( 'avarias_js.js', __FILE__ )); 

}

how do i call the function 'limpar()' on the javascript file with a click of a button?

PHP runs on the server side and Javascript runs on the client side (unless you are using Node.JS) You will want to just add Javascript markup into the HTML page so that it will call the Javascript code. There is no need to have PHP call to client-executed Javascript.

From what I read, basically you will want to insert an HTML button.

<button onclick="limpar();">Click Here!</button>

HTML is the way to go for this.. If I have understood you correctly. Or you can echo the HTML code in PHP. Whatever floats your boat.

you have to call your function inside javascript with something like this (use of jquery):

avarias_js.js :

$(document).ready(function(){
    $("#buttonId").click(limpar);
});

function limpar(){
    alert('something');
}

If you enqueue avarias_js.js properly (make sure its loading on the front side with your browser's developer tools) you can use that JS file and the functions within it.

To use function limpar() create a button in HTML on any page or post template that avarias_js.js is loading on like so:

<input name="butt" type="button" id="butt">

Within your JS use this jQuery snippet to "listen" for a click on the button:

$("#butt").on("click", function(event){
    // alert($(this).text());
    limpar();
});

I would recommend researching AJAX if I interpret your question's goals correctly. Within WordPress it is a bit more complicated than standard AJAX calls to PHP.

NOTE: @dougjore method will immediately fire the function on click. My code listens for a click.

<?php
echo '<!script type="text/javascript">limpar();<!/script>'
?>

Remove the ! after each "<", otherwise stackoverflow wont let me post. I did not test it, just suggesting. Regards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM