views:

42

answers:

2

Hello. How do i make PHP work with JS? I mean more like, i want to check if the user is logged in or not, and if he is then it will: $("#message").fadeIn("slow"); ..

How should i do this? I have an idea maybe have a file that checks it in php, and then it echo out 1 or 0.

And then a script that checks if its getting 1 then do the message fade in.. But im not as so experienced to script that in JS

+3  A: 

You cannot directly pass variables from Javascript to PHP because the PHP run on the server before it's sent to the client. But you can 'pass' variables from PHP to Javascript.

For example:

echo('<script type="text/javascript'> var phpvar = '.$variablefromphp.';</script>');

However, you can manipulate what javascript your browser will print. You can first check if the user is logged in in PHP, and based on that, conditionally print the HTML and Javascript.

For example

if($user->logged_in())
{
  echo('<script type="text/javascript">$("#message").fadeIn("slow");</script>');
}
else
{
  //php function
  generateLoginBox();
}
Stanislav Palatnik
Thank you, that worked!!
Karem
Your welcome :)
Stanislav Palatnik
A: 

I only javascript to enhance user experience. You should make your application work even when javascript turned off.

With the javascript enabled, you can add an enhanced experience, such as animated page element, AJAX request, etc.

In case of login state, you should have a way to know it in PHP script. Then in the output, you can have a conditional block that only executed if the login state is true. You can put anything you want here.

Javascript can be working in a static HTML page. You can use this to create a simple test for the code that you wrote, to see if it working as you want. Read the documentation in http://www.jquery.com/, there are many links there to many examples.

Donny Kurnia
Thank you for the information.
Karem