www.webdeveloper.com
Results 1 to 4 of 4

Thread: Javascript & PHP

  1. #1
    Join Date
    Oct 2009
    Posts
    3

    Javascript & PHP

    Hi

    I have a file x.php. In that i included y.js file(external javascript file).


    I want to use a variable from x.php in the y.js file. How can i do this.

    For example

    Code x.php

    PHP Code:
    <?php
    $username
    =$_SESSION['USERNAME'];
    ?>
    y.js
    Code:
    var username =<?php echo"$usename";?>
    alert(usernmae);
    In the y.js var username =<?php echo"$username"?> is wrong one. How can i get the php variable into the external file.

    Thanks
    Sara

  2. #2
    Join Date
    Oct 2009
    Posts
    658
    Just wondering why you want to access server side variable in client side script? Would Cookies help in this situation? Its at least more secure than what your approach.

  3. #3
    Join Date
    Oct 2009
    Posts
    3

    Thanks

    Thanks for your reply. I new to this. Can you explain how can do with cookies?

  4. #4
    Join Date
    Oct 2009
    Posts
    658
    On the code behind (php)
    Code:
    <?php
    if (!isset($_COOKIE["user"]))
       setcookie("user", "your username whereever you get this", time()+3600);
    else
        ;
       //what you do when its set
    ?>
    On your client side

    Code:
    function getCookie(c_name)
    {
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
    }
    Hope that helps.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles