0

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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Asghar
  • 2,336
  • 8
  • 46
  • 79

3 Answers3

3

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>
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
  • This did not worked. its redirecting properly. but mixpanel.track function does not seems to worked. but if i replace insert alert(); after the mixpanel.track function. then both works fine. but alert() is problem that i cant show on my page. – Asghar Aug 29 '12 at 14:53
  • 2
    @Asghar: What is `mixpanel.track`? My guess is it the page is redirecting before it's finished. – gen_Eric Aug 29 '12 at 14:55
  • 1
    @Asghar: Why do you want to redirect after this? What are you trying to do? – gen_Eric Aug 29 '12 at 14:56
  • mixpanel is analytics API. i am tracking my user login. when some users logins to my system i track to analytics and the redirect to page that should be shown after user logins. – Asghar Aug 29 '12 at 15:16
1

You should forward your user with javascript as well. Something like window.location = '<?php echo $domain_name ?>/services.htm';

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
-1

You can redirect using Javascript itself after using your function:

window.location = 'http://www.example.com';

Alternative, you can use Ajax based solution; but it has to be combined with window.location, where location is given by the php script called by ajax.

check123
  • 1,989
  • 2
  • 22
  • 28