0

I am trying to get the user session from a PHP script into jQuery, but the result is empty. If I use the code in a PHP script it is working properly.

How can I make this work?

<script>
jQuery(document).ready(
   function(){
       var user = '<?php echo $_SERVER['LOGON_USER']; ?>';

       alert(user);
       $('#answer83148X78X346').val(user);
   }
);
</script>
8
  • 4
    The code should work fine. The problem must be in a different part of your application Commented May 22, 2013 at 15:20
  • 5
    Probably, instead of $_SERVER['LOGON_USER'] you should try to use $_SESSION['LOGON_USER']. Commented May 22, 2013 at 15:23
  • 2
    What happens if LOGON_USER contains a single quote, I wonder? ) Commented May 22, 2013 at 15:30
  • yep, @raina77ow is right. use addslashes($_SESSION['LOGON_USER']) Commented May 22, 2013 at 15:33
  • 2
    @hek2mgl Actually, I meant something like... var user = <?= json_encode($_SESSION['LOGON_USER']) ?>;. Commented May 22, 2013 at 15:38

2 Answers 2

1

You might want first try to check whether the variable you're using is correct by logging an output of $_SESSION['LOGON_USER'] or whatnot. In this case, you can easily do this by checking the resulting HTML page's source code.

Also, when serializing values for JavaScript you should escape them to prevent XSS attacks - i.e., filter value through htmlspecialchars function - or better serialize it as JSON, because it handles all types of values, not only strings.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 done ..... :) But you should use $_SESSION['LOGON_USER'] instead of $_SERVER
0

here is my solution:

  1. i created a authuser.php with the following code:

  2. then i retrieved via jquery.get the result from authuser.php and set the textfield with this data:

    $( document ).ready(function() {

    $.get("authuser.php", function(data) {
    alert("Data Loaded: " + data); $('#answer83148X78X346').val(data); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.