-7

I tried to call php function from javascript the code is shown below,

<html>
<head></head>
<body>
<script type="text/javascript" >
    function header()
    {
       <?php
       header("Location:http://www.google.com");
   ?>
    }
 </script>
 <br/><input type="button"  onclick= "header();" value="Google" />
</body>
</html>

When I run this code before, i.e click the button, the page is automatically directed to www.google.com , my requirement is clicking on the button and directing to the respective page, What is wrong in thi code?

Roland Ewald
  • 4,630
  • 3
  • 35
  • 49
user2971474
  • 37
  • 1
  • 4

5 Answers5

2

If you simply want to redirect to a new url then you can use window.location for this.

function header()
    {
       window.location = "http://www.google.com";
    }

You can find check this answer for more

1.How to redirect to another webpage in JavaScript/jQuery?

Community
  • 1
  • 1
웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
0

why dont you use:

function header(){
window.location="http://google.com";
}
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
0

This should be:

function header()
    {
       window.location="http://www.google.com";
    }
0

PHP is always executed before the page gets to the browser, so... Yeah. You can't store a php function in JavaScript to happen when you click a button. You CAN use PHP to print out text that is JavaScript and fill in variables while the page is created.

If you just want to redirect, use JavaScript:

<script>
  document.location='http://google.com';
</script>
JAL
  • 21,295
  • 1
  • 48
  • 66
0

you CANT interact php with javascript i suggest you read their manuals first

php is server side, hence every bit of its code is already parsed and rendered when you see the page in the browsers thus the result of above code is an immediate redirection to google.com at page load [if no error occurred]

one of the ways of this interaction is using AJAX, it can be used to do server specific functions using data from the client. But URL redirection isnt a good use of it

ManZzup
  • 526
  • 4
  • 12