Pauet
Pauet

Reputation: 1

Opening a window in Javascript with the value of a PHP variable

I would like to open a window with a 5 second delay when a button is clicked. I'm trying:

<script type="text/javascript">
function sample() {
   setTimeout(function() {
       window.open('<?php echo esc_attr(wpcoupon_coupon()->get_go_out_url()); ?>', '_self');
   }, 5000); 
}
</script>  

which I call in the onclick attribute of the <button>:

<button class="ui right labeled icon button btn btn_secondary" onClick="sample();">
    <i class="copy icon"></i>
    <span><?php esc_html_e('Copy', 'wp-coupon'); ?></span>
</button>

The problem is that <?php echo esc_attr(wpcoupon_coupon()->get_go_out_url()); ?> doesn't return the correct value, and correct URL doesn't open.

What could be going wrong?

Upvotes: 0

Views: 225

Answers (2)

mscdeveloper
mscdeveloper

Reputation: 2889

Is the page address correct?

esc_attr(wpcoupon_coupon()->get_go_out_url())

For test your script in php file use construction:

<?php
   //php code
?>
<script>
function sample() {
   setTimeout(function() {
       window.open('<?php echo('https://google.com'); ?>', '_self');
   }, 5000);
}
</script>
<button class="ui right labeled icon button btn btn_secondary" onClick="sample();">test</button>
<?php
  //php code
?>

Upvotes: 0

&#193;lvaro Romero
&#193;lvaro Romero

Reputation: 61

You need ajax to read that php variable asynchronously from javascript. Otherwise i think your question is better answered here:

Get variable from PHP file using JQuery/AJAX

Upvotes: 1

Related Questions