-1

I got some php code like this to redirect my page inside one php function:

   <script>
   function a(){
      <?php
         header('Location: http://www.localhost.com/');
      ?> 
    }
   </script>

I will like to know if there is any way to stop this to redirect inmediatly when i load my page, and if it is possible to do it with some Javascript or JQuery, cause I tried it with JS and I couldn't find a way to do it .

arnausd
  • 25
  • 1
  • 7
  • 6
    PHP is sending header() *way* before the DOM is loaded, and probably quite a while before *any* JavaScript will execute. – Kevin_Kinsey Jan 27 '16 at 20:41

2 Answers2

0

I don't think you can stop it when it comes from php, but you can have the redirect with javascript. See this for example.

Community
  • 1
  • 1
aemorales1
  • 312
  • 3
  • 13
0

The php end of it will process before the javascript does. I'm not sure why you have it set up this way but you will need to come up with a different way of doing things. Perhaps not using PHP at all would be your best option here and just using a javascript command to change the page instead.

Such as:

<script>
   function a(){
      window.location = "http://www.localhost.com/";
    }
</script>


<button onclick="a()">Go</button>
Eric
  • 476
  • 2
  • 8
  • 20
  • I tried your answer with window.location but i call this function with a button and it seems to don't do anything, but if i put and alert() before i can saw the message, do you know what can this bbe for? – arnausd Jan 28 '16 at 08:33
  • I'm sorry, I don't know why it wouldn't work. I just barely popped this into an .html file to test it to make sure nothing was wrong and it worked like a charm. There may be something else in your code interfering. – Eric Feb 01 '16 at 21:40