Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

calling javascript function before PHP Header

I am using this code to call a javascript function and then redirect PHP page.

<script type='text/javascript'>

mixpanel.track('login: Login ', {'page name' : document.title, 'url' : window.location.pathname});
</script>;  

<?php
        header("Location:".$domain_name."/services.htm");

?>

But this code is not working, if i don't redirect then js function works fine.

i also tried ob_start(); and ob_end_flush(); but nothing worked. How can use JS function before redirect. i am new to JavaScript and PHP header function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP runs on the server and JavaScript runs in the browser. You can't just mix them together like that.

What you need to do is do the redirect with JavaScript, and not PHP.

<script type='text/javascript'>
    mixpanel.track('login: Login ', {'page name' : document.title, 'url' : window.location.pathname});
    window.location = '<?=$domain_name?>/services.htm';
</script>

UPDATE: The redirect is triggering before mixpanel.track is complete. You need to pass a function to the callback docs, so it runs once it's done.

<script type='text/javascript'>
    mixpanel.track('login: Login ', {
        'page name': document.title,
        'url': window.location.pathname
    }, function(){
        window.location = '<?=$domain_name?>/services.htm';
    });
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...