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?

6
  • pop up blockers will most likely block the window. Commented Jun 21, 2018 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. Commented Jun 21, 2018 at 11:55
  • This is mixture of JS and PHP; such a thing is not possible. You should try another approach. Commented Jun 21, 2018 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 Commented Jun 21, 2018 at 12:03
  • Ok ill try to explain better: Commented Jun 21, 2018 at 12:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

No knowledge about that.
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
?>

3 Comments

yes, if i echo esc_attr(wpcoupon_coupon()->get_go_out_url()) it shows example.com/go-to-store/1198 so is correct, but with the function it shows another url example.com/go-to-store/202.
Maybe use: var url='<? echo esc_attr(wpcoupon_coupon()->get_go_out_url()); ?>'; and : window.open(url, '_self');
think php problem because with google.com it works correctly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.