-3

I have the following javascript code:

function like(){
  if(loged) {
    if(liked) {
      likes-=1;
      liked = false;
      document.getElementById('alike').src = "img/icons/like.png";
    } else if(disliked) {
      dislikes-=1;
      disliked = false;
      likes+=1;
      liked = true;
      document.getElementById('alike').src = "img/icons/like1.png";
      document.getElementById('adislike').src = "img/icons/dislike.png";
    } else {
      likes+=1;
      liked = true;
      document.getElementById('alike').src = "img/icons/like1.png";
    }
  } else {
    <?php header("Location:login");?>
  }
}

I want to redirect the user to the login page how can i user php inside javascript to this. I do not want to have to use any other things like ajax etc. Thanks.

clinton3141
  • 4,751
  • 3
  • 33
  • 46
Jack
  • 31
  • 8

2 Answers2

1

You do not need to use PHP header() to redirect with JS. You can simply use the window.location property:

window.location.href = "your_url";

//or

window.location = "your_url";

//or

location.href = "your_url";

//or

location = "your_url";
Rax Weber
  • 3,730
  • 19
  • 30
1

As mentioned in the other comments, to redirect in javsascript you want to use something like window.location.href = "your_url";.

Here's a bit of extra information as well to help you out in the future, as you seem to have misunderstoon the relationship between PHP and JavaScript.

In a nut shell, you can't call PHP functions from javascript. PHP code and javascript code run at two very different times in the request cycle. PHP is run by the server and JavaScript is run by the client (browser)

PHP

When you load a webpage a request will be sent by your client (browser) to a server, which receives it and returns a response.

PHP runs on the receiving server and it's job, very simply put, is to generate a response to send back to the browser. So it may generate html, javascript, etc.

You can use PHP to output html for example <?php echo 'Hello world'; ?>.

Once PHP has sent it's response that's it, it's game over for PHP.

HTML and JavaScript

The requesting browser will receive the response that the server sent and will then handle it. For HTML it will render a page and any JavaScript will be run.

Javascript can't interact with the PHP in anyway at all, since the PHP code was run on the server, while the javascript runs on the client.

It's important to understand the different between client and server, otherwise you'll find yourself running into similar problems going forward :)

ArranJacques
  • 814
  • 3
  • 9
  • 9