0

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?

Keith Gaughan
  • 21,367
  • 3
  • 32
  • 30
Pauet
  • 1
  • 2
  • pop up blockers will most likely block the window. – epascarello Jun 21 '18 at 11:54
  • 1
    So what is the value written when the page loads, that is the value. View the page source. Issue would be with the PHP code. – epascarello Jun 21 '18 at 11:55
  • This is mixture of JS and PHP; such a thing is not possible. You should try another approach. – ata Jun 21 '18 at 12:00
  • Of course is such mixing possible, but it won't work as expected sometimes. In this case, you should explain which URL is opened and what you expect – Nico Haase Jun 21 '18 at 12:03
  • Ok ill try to explain better: – Pauet Jun 21 '18 at 12:12
  • get_go_out_url() ); ?> returns out url value correctly. I have a button and i need when someone click it start a counter of 5 sec, and then out url loads. – Pauet Jun 21 '18 at 12:16

2 Answers2

1

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

0

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
?>
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17
  • yes, if i echo esc_attr(wpcoupon_coupon()->get_go_out_url()) it shows http://www.example.com/go-to-store/1198 so is correct, but with the function it shows another url http://www.example.com/go-to-store/202. – Pauet Jun 21 '18 at 17:06
  • Maybe use: var url=' echo esc_attr(wpcoupon_coupon()->get_go_out_url()); ?>'; and : window.open(url, '_self'); – mscdeveloper Jun 21 '18 at 17:15
  • think php problem because with google.com it works correctly – Pauet Jun 21 '18 at 18:46