2

I use session flag in javascript for IF function. If session flag is 1, the javascript will show a specifict div on click. I have tried it manually, but the code doesn't seem to work.

This is my JS code:

$(document).ready(function(){
check = <?= $_SESSION['flag'] ?>;
$("#bag").click(function(){
    if(check==0){
        $("#login").show();
        $("#notlogin").hide();
    } else {
        $("#login").hide();
        $("#notlogin").show();
    }
});
}); 

And this is the session in the head of html file:

<?php @session_start();
$_SESSION['flag']=0;
?>

Please check it in the fiddle: http://jsfiddle.net/9mm5ougu/

config-haslogin.php

<?php
error_reporting(E_ALL ^ E_NOTICE); 
ini_set("display_errors", 1);
mysql_connect("mysql.com","name","password") or die("cannot connect");
mysql_select_db("databasename") or die("Fail here");
$myemail= $_POST['myemail'];
$mypassword= $_POST['mypassword'];
$sql= "SELECT * FROM user WHERE myemail='".$myemail."' and mypassword='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
echo "Login successful";
$_SESSION['flag']=0;
header("Location:index.php");
}
?>
Al Kush
  • 278
  • 3
  • 15
  • it's a normal behavior, you can't do that, `= $_SESSION['flag'] ?>` is `PHP` code, not `JavaScript`. `PHP` is executed on the server side, `JavaScript` is executed on the client side (at least in your example). – pomeh Sep 01 '14 at 09:22
  • 2
    Do you know about Client Side and Server Side Scripting? How can you define server side code in jsfiddler? – Amit Soni Sep 01 '14 at 09:25
  • I need to do that, is there a different method for that? – Al Kush Sep 01 '14 at 09:25
  • 2
    With Javascipt I always find it useful to look at the error message in the browser's console window. It would have probably given you a hint at to what was wrong. (ie. not quoted, or not interpreted) – KIKO Software Sep 01 '14 at 09:38

3 Answers3

3

You can't put PHP code into a JavaScript file, because PHP is interpreted on the server side, while JavaScript is interpreted on the client side (at least here in your use case).

If you really have to do conditional treatment based on the PHP $_SESSION value, you have multiple choices (listed from the worst to the best one IMHO):

Solution 1: use a dynamic JavaScript file (the worst)

Put PHP code in your JavaScript file, but use the .php extension instead of .js. Your JavaScript code would look like something like this:

file.js.php

$("#bag").click(function(){
    <?php if ($_SESSION['flag'] === 0): ?>
        $("#login").show();
        $("#notlogin").hide();
    <?php else: ?>
        $("#login").hide();
        $("#notlogin").show();
    <?php endif; ?>
});

And you can include this PHP file as a JavaScript file:

index.php

<script src="file.js.php"></script>

This is the worst solution: - as you're mixing both languages, your file will soon become unreadable - because the file is now dynamic, the user's browser can't put it on the client-side cache - you're using PHP server's resources where it's not really necessary - you can't deploy your file on a CDN, or on a simple server dedicated to serve static file - you can't minify your JavaScript file

Solution 2: use two different JavaScript files

Create two different JavaScript file, one for logged in user and one for logged out. Load the correct file using the $_SESSION value.

loggedOut.js

$("#bag").click(function(){
    $("#login").hide();
    $("#notlogin").show();
});

loggedIn.js

$("#bag").click(function(){
    $("#login").show();
    $("#notlogin").hide();
});

index.php

<body>
    <!-- page content here -->


    <?php if ($_SESSION['flag'] === 0): ?>
        <script src="loggedIn.js"></script>
    <?php else: ?>
        <script src="loggedOut.js"></script>
    <?php endif; ?>

</body>

This solution is better than the first one because it resolves almost all points: the file is cached on the client and you don't mix PHP and JavaScript code. But this is not the best solution you can have, because it brings a lot of code duplication and it would be harder to maintain the code base.

Solution 3: bring the model client side (or sort of)

You can pass your data model to the JavaScript file, and use it directly from there. As an example, you can have a class name on the <body> tag that depends on the $_SESSION['flag'] value, and your JavaScript file will behave differently based on this value. Here is an example:

index.php

<?php
$className = $_SESSION['flag'] ? 'logged-in' : 'logged-out';
?>

<body class="<?php echo $className; ?>">
    <!-- page content here -->

    <script src="yourFile.js"></script>
</body>

yourFile.js

$(document).ready(function(){

    var isLoggedIn = $('body').hasClass('logged-in');

    $("#bag").click(function() {
        if (isLoggedIn)
        {
            $("#login").show();
            $("#notlogin").hide();
        }
        else
        {
            $("#login").hide();
            $("#notlogin").show();
        }
    });

});

If this class is only used by the JavaScript code (it means this class will no be used in the CSS code), you should prefix it with this js- to differentiate it from real CSS class names.

pomeh
  • 4,742
  • 4
  • 23
  • 44
  • Wow, the explanations are so complete. I have to accept this as the best answer. I will give it a try and be back soon to ask a question again if I found a problem. Thank you for your spare time. Cheers! – Al Kush Sep 01 '14 at 11:38
  • 1
    @AlKush you're welcome. Let me know if you have questions :) To me, it's important you understand what was the problem IMHO in your initial approach, not just to have a "copy/paste" answer – pomeh Sep 01 '14 at 11:55
  • How can the file of index.php (in the solution 2) know if the session flag is 0 or not? Because it always result the same event eventhough the user has login succesfully. – Al Kush Sep 02 '14 at 07:58
  • you have to start the session with the `session_start` function – pomeh Sep 02 '14 at 08:33
  • I have started it with session_start but the result is still the same. – Al Kush Sep 02 '14 at 12:27
  • @AlKush it does work for me, have a look: logged out (http://3v4l.org/SeKjG#v523) and logged in (http://3v4l.org/PtmHb#v523). You can see in both examples that the right file is loaded (even if they don't exist in my example), and the value of `$_SESSION['flag']` is correct (use `var_dump` to see it). Do you have any error when starting the the session ? Use `session_start()` instead of `@session_start()`, and `error_reporting(E_ALL); ini_set('display_errors', 1);` to display all PHP errors. – pomeh Sep 02 '14 at 14:42
1

While you are accessing PHP variables inside Javascript, enclose that within quotes like

check = "<?= $_SESSION['flag'] ?>";

Check this fiddle.

Jenz
  • 8,280
  • 7
  • 44
  • 77
  • 1
    `check = ;` (note, no quotes in the javascript side) is better, because it properly encodes the content of the variable without forcing it into a string (or tripping over stray quotes in the value). – DCoder Sep 01 '14 at 09:28
  • 1
    in any case, you can't put PHP code into a JavaScript file. And IMHO it would be better to user `json_encode($_SESSION['flag'])` directly, it avoid simple/double escape hell and a lot of other tricky stuff – pomeh Sep 01 '14 at 09:28
  • @pomeh..Anyway it is possible to do like that. I just helped the user to meet his requirement in the way he needs. – Jenz Sep 01 '14 at 09:31
  • @Jenz: I agree you don't deserve a minus for seeing a bug. But pomeh is right as well, it doesn't look very nice, but that's not your doing. – KIKO Software Sep 01 '14 at 09:41
  • @Jenz, it works, thanks. But why when I try to change the "check" value with 1 it doesn't change the if function? – Al Kush Sep 01 '14 at 09:46
  • @AlKush this solution does not work, it just remove a bug that you have. As I said, you can't put PHP code into JS file. I'm writing another answer right now to explain that – pomeh Sep 01 '14 at 09:48
  • @AlKush..That else condition works. As you are setting the div as hidden that change won't be visible I think. – Jenz Sep 01 '14 at 09:48
  • 1
    Jenz while your remark is good, IMHO it might no be the right answer. PHP in JavaScript file can't work, as PHP in a JSFiddle can't either, it's **not interpreted**. Did you at least test your own code ? Try this `console.log(check)` or `echo 'hello from PHP';` in JSFiddle, you'll be surprised. You can't say 'it works, check this fiddle' and have PHP code in that fiddle, I don't have to test it to know it's not working ! So in that way, your answer is not valid IMHO: the tip is good (using quotes), but the demo doesn't work, and it doesn't resolve the initial problem (mixing PHP with JS). – pomeh Sep 01 '14 at 11:51
  • 2
    @KIKOSoftware I think it's our doing to explain **what** is wrong in OP approach, not only to solve is problem in a "one-shot" way. If we don't explain it, OP will ask again and again the same sort of questions because it doesn't understand **where is the problem at first** (mixing server side and client side code in this case). The strength of StackOverflow is its community and its users, and sometimes answers are just more than answers, they are way more than that, have a look at the accepted answer for this question: http://stackoverflow.com/q/23569441/827168. – pomeh Sep 01 '14 at 11:52
  • @pomeh: Yes, you're right, and I've seen that you've written a very nice answer. I prefer your second solution. – KIKO Software Sep 01 '14 at 12:48
1

Use AJAX to get the data you need from the server.

For example create get-data.php:

<?php @session_start();
_SESSION['flag'] = 0;
json_encode(_SESSION['flag']);
?>

Call it from ajax:

$(document).ready(function(){ // your DOM loaded
    $.ajax({
        url: '/get-data.php',
        success: function(response){
            $("#bag").click(function(){
                if(JSON.parse(response) == 0){
                    $("#login").show();
                    $("#notlogin").hide();
                } else {
                    $("#login").hide();
                    $("#notlogin").show();
                }
                });

        },
        error: function(){
            alert('data not loaded');
        },
         complete: function(){

       }
    })

})
Trone
  • 134
  • 7
  • It is interesting, I have voted it up. My question is: what is it in the get-data.php? Is it the user information such as the username and the password? Thanks. – Al Kush Sep 01 '14 at 11:19
  • 1
    the file contains a simple code that returns the user to the necessary data, it can be used to obtain the required parameters and for storing data, for example, you can create a template and use it for the return parameters, such as isset($success) ? ( $success ? true : false) : true, 'data' => $data, 'message' => empty($message) ? '' : $message) ) ?> Where success - it was successful your query or not , message - a message in case of an error, the date - it's your data – Trone Sep 01 '14 at 11:27
  • I think your code will work if I know how to do that. But the problem is I am still confused between the get-data.php (which you suggest) and the config-haslogin.php (the config php file that get the user information) In the config-haslogin.php I alwo write a session flag (echo "Login successful"; $_SESSION['flag']=0; exit(header("Location:index.html"));) – Al Kush Sep 02 '14 at 07:52