Results 1 to 8 of 8

Thread: How to pass dynamic php variable to javascript variable.

  1. #1
    Join Date
    Jun 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How to pass dynamic php variable to javascript variable.

    Hi,

    Can anyone help me how to pass a javascript variable to Session variable in php..
    This is my whole JavaScript code

    Code:
    <script type="text/javascript" charset="utf-8">
    
    function TicketAss(ticketno,cname,sVal) {
        if (window.confirm('Assign this ticket number ' + ticketno + ' to ' + sVal.val())) {
    
     //this value must pass to the session variable
    <?php echo  $_SESSION['MISPIC'] ?>= sVal.val() ;
           document.forms['assigned'].submit();
    
    		
        }else{
    	sVal.val(0);
    	};
    }
    
    var forms1 = document.getElementsByTagName('assigned'),
        i;
    for (i = 0; i < forms1.length; i += 1) {
        if (forms[i].className === 'assigned') {
            forms[i].onchange = TicketAss;
        }
    }
    </script>

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,925
    Thanks
    43
    Thanked 3,190 Times in 3,154 Posts
    Blog Entries
    12

    Default

    First off, you seem confused. The title of your post asks:

    How to pass dynamic php variable to javascript variable
    While the text in your post asks:

    Can anyone help me how to pass a javascript variable to Session variable in php
    I'm assuming you mean the latter, javascript to PHP.

    I see that you use:

    Code:
    sVal.val()
    That's a jQuery construct/method and since I don't see it otherwise defined in your post, I'll assume you're using jQuery.

    If so, you can also use jQuery's ajax() method to post to a page that can set the variable for you without leaving the current page.

    For that you will need a separate PHP page, let's call it mypost.php and on it have:

    PHP Code:
    <?php
    session_start
    ();
    $_SESSION['MISPIC'] = $_POST['MISPIC'];
    ?>
    Now in your javascript where you have (which I'm sure you know doesn't work):

    Code:
    <?php echo  $_SESSION['MISPIC'] ?>= sVal.val() ;
    You may instead do (untested, for now):

    Code:
    jQuery.ajax({
    	url: 'mypost.php',
    	type: 'POST',
    	data: 'MISPIC=' + sVal.val(),
    });
    That's it. I'll test this in a little while. If there are any problems, I'll let you know.
    Last edited by jscheuer1; 06-10-2011 at 05:39 AM. Reason: syntax
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jun 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Hi Thanks for the reply.

    Here is my whole code.where i will get the data MISPIC..
    PHP Code:
    <?php
    session_start
    ();
    if(isset(
    $_SESSION['username'])){
    include_once(
    "conn.php");



      
    $newtickets=array();

        
    $newtickno=mssql_query("Select * from tblTicket where TickNo not in (select TicketNo from tblAssign)");
         while(
    $newticket mssql_fetch_array($newtickno)){
            
    $newtickets[] = $newticket;
            }
        
    $Assign mssql_query("Select * from MISPIC ");
        while(
    $AssignOption mssql_fetch_assoc($Assign)){
            
    $AssignOptions[] = $AssignOption;
        }
        
    ?>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8" />

        <script type="text/javascript" language="javascript" src="jquery./jquery.js"></script>
        <script type="text/javascript" language="javascript" src="jquery./jquery.dataTables.js"></script>
        <script type="text/javascript" charset="utf-8">
            $(document).ready(function() {
            $('#example').dataTable();
            } );
        </script>    
        <script type="text/javascript" charset="utf-8">


    </script>

    <?php echo '<meta http-equiv="refresh" content="60;url="UnAssignticket.php">';?>
          <style type="text/css">
    form {
        float:left;
    }
    </style>
        </head>
            
    <body id="dt_example">
    <br/>
    <br/>
    <p>
    <table  BORDERCOLOR="#0B0B0B" border='1' bgcolor="#F5F5FA" width="100%"  align='center'>
    <tr>
        <td >
            <img src='img/pend.png'>
        </td>
    </tr>
    <tr>
        <td align='center'>
            <div align='left' id="containerpend">
                <div id="demo">
                    <table BORDERCOLOR="#0B0B0B"  frame="box" cellpadding="0" cellspacing="0" frame="box"  class="display" id="example"> 
            
                <thead>
                    <tr>
                        <th><a title="Ticket Number">Ticket No.</a></th>
                        <th><a title="Ticket Create By">Create By</a></th>
                        <th><a title="Ticket Create Date">Create Date</a></th>
                        <th><a title="Date Assigned">Date Assigned</a></th>
                        <th><a title="Problem Error">Problem Description</a></th>
                        <th><a title="Ticket Assigned To">Assign To</a></th>
                        <th><a title="User Action">Action</a></th>
                    </tr>
                </thead>
                <tbody>            
            
                            <?php foreach($newtickets as $newticket) { ?>
                                <tr class="GradeA">
                                    <td class='center'><?php echo "<a href='ticketinfo.php?id={$newticket['TickNo']}' title='View Ticket'>".$newticket['TickNo']."</a>"?></td>
                                    <td class='center'><?php echo $newticket['UserName'];?></td>
                                    <td class='center'><?php echo $newticket['DateCreate'];?></td>
                                    <td class='center'><?php echo $newticket['DateAssign'];?></td>
                                    <td class='center'><?php echo $newticket['Category']." (".$newticket['Subcat'].")"?></td>
                                    <td class='center'><?php echo $newticket['AssignTo'];?></td>
                                    
                                    <td class='center'>
                                
                                        <form id='assigned'  name="assigned" class='assigned'  action='asstoticket.php' method='POST'  >
                                        <?php     $_SESSION['assignticketno']=$newticket['TickNo']; 
                                    
                                            
    ?>
                                            <select style="width:100%" id='assignto' name='assignto' onchange="TicketAss('<?php echo $newticket['TickNo'];?>','<?php echo $newticket['UserName'];?>',$(this));" >
                                            
                                                <option value="0">Please Select</option>
                                                
                                                <?php foreach($AssignOptions as $TransferOption){ 
    //this line
                                                
    echo '<option  value="'$TransferOption['MISPIC'], '">'$TransferOption['MISPIC'], '</option>'
                                            }
                                                
    ?> 
                                            </select>
                                
                                        </form>
                                    </td>
                                
                                </tr>
                        <?php }    ?>
                </tbody>
                    <tfoot>
                        <th>Ticket No</th>
                        <th>Create By</th>
                        <th>Create Date</th>
                        <th>Date Assigned</th>
                        <th>Problem Description</th>
                        <th>Assign To</th>
                        <th>Action</th>        
                </tfoot>            
            </table>
        
                </div>
            </div>
        </td>    
    </tr>
    </table    >
    </p>


    <script type="text/javascript" charset="utf-8">

    function TicketAss(ticketno,cname,sVal) {
        if (window.confirm('Assign this ticket number ' + ticketno + ' to ' + sVal.val())) {

           document.forms['assigned'].submit();

            jQuery.ajax({
        url: 'astoticket.php',
        type: 'POST',
        data: 'MISPIC=' + sVal.val(),
    })
        }else{
        sVal.val(0);
        };
    }

    var forms1 = document.getElementsByTagName('assigned'),
        i;
    for (i = 0; i < forms1.length; i += 1) {
        if (forms[i].className === 'assigned') {
            forms[i].onchange = TicketAss;
        }
    }

    </script>

        <style type="text/css" title="currentStyle">
            @import "css/demo_page.css";
            @import "css/demo_table.css";
        </style>

        </body>
        </html>
    <?php
        
    }else{ //not logged in
        
    header('location: login.php');
    }
    ?>

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,925
    Thanks
    43
    Thanked 3,190 Times in 3,154 Posts
    Blog Entries
    12

    Default

    Are you having any problems with my suggestion? Because what you have there looks OK to me as long as astoticket.php is a separate page and has this and only this (it could possibly include other valid code as long as it doesn't throw a server/PHP error) on it:

    PHP Code:
    <?php 
    session_start
    (); 
    $_SESSION['MISPIC'] = $_POST['MISPIC']; 
    ?>
    However I have no idea what your other objectives here are. All this will do is set the session variable MISPIC whenever this section of the code is executed:

    Code:
            jQuery.ajax({ 
        url: 'astoticket.php', 
        type: 'POST', 
        data: 'MISPIC=' + sVal.val(), 
    })
    I do see one potential problem with the code, but even though I'm pretty sure it's wrong, it might not be preventing what you need/want as an outcome. To wit:

    Code:
    var forms1 = document.getElementsByTagName('assigned'), 
        i; 
    for (i = 0; i < forms1.length; i += 1) { 
        if (forms[i].className === 'assigned') { 
            forms[i].onchange = TicketAss; 
        } 
    }
    In HTML there's no valid tag named assigned, and the code doesn't even show any invalid ones. So, although this section of code may possibly run without throwing an error, it won't actually do anything. But that might not matter because you have:

    PHP Code:
                                            <select style="width:100%" id='assignto' name='assignto' onchange="TicketAss('<?php echo $newticket['TickNo'];?>','<?php echo $newticket['UserName'];?>',$(this));" > 
                                             
                                                <option value="0">Please Select</option> 
                                                 
                                                <?php foreach($AssignOptions as $TransferOption){  
    //this line 
                                                
    echo '<option  value="'$TransferOption['MISPIC'], '">'$TransferOption['MISPIC'], '</option>';  
                                            } 
                                                
    ?>  
                                            </select>
    which hard codes TicketAss to each PHP generated select in that part of the loop and assigns the $TransferOption['MISPIC'] as values for the options, thus fulfilling what the ajax() code will need to run.

    What will not happen as a result of the ajax() function is any real time update of the database, or the page generated by the code in your post. All it will do is set the session variable MISPIC.
    Last edited by jscheuer1; 06-10-2011 at 11:28 AM. Reason: add detail and question at the beginning
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Jun 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    that is what i have done on the first place..

    I will just post my asstoticket.php so you can understand more..

    Here is where i must post my MISPIC but after the page reloaded my value for $_POST['MISPIC'] get a empty value..


    PHP Code:
    <?php
    session_start
    ();
    if(isset(
    $_SESSION['username'])){
    include_once(
    "conn.php");
    echo
    $_SESSION['MISPIC']=$_POST['MISPIC'];
    $pend=mssql_fetch_assoc(mssql_query("Select * from tblTicket where TickNo='$_SESSION[assignticketno]'"));
    $img=mssql_fetch_assoc(mssql_query("Select * from tblattachment where TicketNo='$_SESSION[assignticketno]'"));
    $image1=trim($img['image1']);
    $image2=trim($img['image2']);
    $image3=trim($img['image3']);

    ?>
    <html>
    <head>
        <script src="jquery/jquery.min.js"></script>
        <script type="text/javascript" src="jquery/jquery.validate.js"></script> 
        <script>
            $(document).ready(function(){
                $.validator.addMethod("noSpecialChars", function(value, element) {
                      return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
                  }, "<br/><font size='3' color='#FF0000'>Username must contain only letters, numbers, or underscore.</font>");
                $("#msg").validate({
                  rules: {
                  description:"required",
                    severity:"required"
                    
                 }
                });
            });
        </script>
    <script>
    function textCounter(field, countfield, maxlimit)
    {
      if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
      else 
        countfield.value = maxlimit - field.value.length;
    }
    function textcount(field,mlimit)
    {
      field.value = field.value.substring(0, mlimit);
    }
    </script>
        
    </head>
    <body onload="document.msg.description.focus();">

    <table  BORDERCOLOR="#0B0B0B" border='1' bgcolor="#F5F5FA" width="80%"  align='center'>
    <tr>
        <td width="100%" align="left" valign="middle">
        <img src='img/assignto.png'>
        </td>
    </tr>

    <td width="100%" align="center" >
    <?php

    date_default_timezone_set
    ("Asia/Hong_Kong");
            
    $dateassign=date("Y-m-d"); 
    if(isset(
    $_POST['Save'])){



    $pend=mssql_fetch_assoc(mssql_query("Select * from tblTicket where TickNo='$_SESSION[assignticketno]'"));
    $img=mssql_fetch_assoc(mssql_query("Select * from tblattachment where TicketNo='$_SESSION[assignticketno]'"));
    $image1=trim($img['image1']);
    $image2=trim($img['image2']);
    $image3=trim($img['image3']);
    if (
    $_FILES['images']['size'] <= 1024 1024){
                  
    $filename=basename$_FILES['images']['name']);
                     
    $add "upload/".$filename;
                     
    $original_name=$filename;
                if(!empty(
    $filename))
                {
            
                    if(
    file_exists($add))
                    {
                            
    $filename rand().$original_name;
                            
    $add "upload/".$filename;
                    }
                    if(
    copy($_FILES['images']['tmp_name'], $add))
                    {
                        
    chmod("$add",0777);
                    }
                }
                echo 
    "send";
                

        }else{

            echo 
    "<font color='#FF000'><p align='center'>(File not send.Attach File exceeds the file limit.)</p></font>";
            

    }


    }
    ?>
    <table align='center' BORDERCOLOR="#0B0B0B">
    <form  name='msg' id='msg' action='asstoticket.php' method='post'  enctype="multipart/form-data">
        <table  align='center'>

        <input type='text' value='<?php echo $_SESSION['MISPIC'];?>' name='assto'>
        
            <tr>
                <td><strong><label>Ticket No : </label></strong><?php echo $pend['TickNo'];?>    </td>    
            </tr>
            <tr>
                <td><strong><label>Create By : </label></strong><?php echo $pend['UserName'];?>    </td>
                <td><b>Assign to : </b><?php echo echo$_SESSION['MISPIC'];?></td>            
            </tr>
            <tr>
                <td><strong>Date Create : </strong><?php echo $pend['DateCreate'] ;?></td>
                <td><strong>Date to be Assign: </strong><?php echo $dateassign;?></td>
            <tr>
            <tr>        
                <td><strong>Category : </strong><?php echo $pend['Category'];?></td>
                <td><strong>Sub-Category : </strong><?php echo $pend['Subcat'];?></td>
            </tr>
            <tr>
                <td>
                    <strong>File Attachment : </strong>
                    <?php 
                        
    if(!empty($image1))
                        {
                        echo 
    "<a href='DLfile.php?download_file=$image1'>File 1</a> &nbsp";
                        }
                        if(!empty(
    $image2))
                        {
                        echo 
    "<a href='DLfile.php?download_file=$image2'>File 2</a> &nbsp";
                        }
                        if(!empty(
    $image3))
                        {
                        echo 
    "<a href='DLfile.php?download_file=$image3'>File 3</a> &nbsp";
                        }
                    
    ?>
                </td>
            
                
                        <td ><b>Severity <font color=red>*</font>: </b>
                        
                            <select class='severity' name='severity' tabindex='2'>
                                <option></option>
                                <option name='low'>Low</option>
                                <option name='Midium'>Medium</option>
                                <option name='High'>High</option>
                                <option name='Critical'>Critical</option>
                            </select>
                        </td>
                        
            </tr>
            <tr>
                
                <tr>
                    <td><strong>MIS Attachment : </strong>
                    <td>
                    <?php 
                    $att
    =mssql_query("Select * from  tblattachassign  where tblattachassign.TicketNo='$id'"); 
                    while(
    $row1=mssql_fetch_assoc($att))
                    { 
    $img=trim($row1['Image']);
                    if(!empty(
    $img))
                        {
                            echo 
    "Date: ".$row1['Date']. " <a href='DLfile.php?download_file=$img'>Attach File</a> <br/>";
                        }
                    }
                    
    ?>
                    </td>
                    </td>
                </tr>
            </tr>        
            <tr><td><strong>Description : </strong><?php echo wordwrap($pend['Description'],70,"\n",true);?></td></tr>    
    <tr>
    <td align='left'>
    <a href="#" onclick="document.getElementById('showattach').style.display=(document.getElementById('showattach').style.display== 'block')?'none':'block';">Attachment</a>
    </td>
    </tr>
    <tr>
    <td align='left'>
        <div  align='left' name='showattach' id='showattach' class='showattach' style="display: none"> 
            <input align='left'  type='file' name='images'>Max File Size 2mb
        </div>
    </td>
    </tr>    


    <br/>
    <table  align='center'>
    <tr>
        <td>
        <tr>
        <td align='left'><b>Comment's/Solution <font color=red>*</font> :</td>
        </tr>
        <tr>
            <td align='left'><textarea rows="7" cols="50" name="description" onKeyDown="textCounter(this.form.description,this.form.remLen,500);" onKeyUp="textCounter(this.form.description,this.form.remLen,500);" >
            </textarea><br><input readonly type=text name=remLen size=3 maxlength=3 value="500"> characters left.</font></td>
        </tr>
        
        <tr>
        <td align='left'>
            <input type='submit' value='Submit' name='Save'  onClick="javascript: var x=window.confirm('Send this message?');if (!x) return(false);" title='Submit a Message'>
            <input type='Reset' value='Reset' name='reset' title='Reset'>
        </td>
        </tr>
    </td>    
    </tr>    
        </table>

    </form>

    <br/>
    </tr>
    </td>
    </table>    
    </body>
    </html>
    <?php
    }else{
        
    header('location:login.php');
    }
    ?>

  6. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,925
    Thanks
    43
    Thanked 3,190 Times in 3,154 Posts
    Blog Entries
    12

    Default

    Three things:

    1. Is it asstoticket.php or astoticket.php? You have it one way in your ajax() code and another in your most recent post.

    2. There's way too much going on in the file (asstoticket.php) from your previous post for me to know if it can reliably set the session variable MISPIC. I said use a separate file for this.

    3. Even if it could (meaning none of the other stuff throws a server side or PHP error, and the asstoticket.php is the file called by the ajax() function), it probably will not because the $_SESSION['MISPIC']=$_POST['MISPIC']; statement is prefixed with an echo directive.


    All I answered was your original question. How to set the PHP session variable from javascript. That's all my answer was intended to do. It was not intended to execute a complex PHP, HTML, and javascript page like the asstoticket.php page you show. It will not import anything from that page to the page with the ajax() function on it. It will not load the asstoticket.php page into the user's browser. The javascript and HTML code on asstoticket.php will be ignored as will any PHP that doesn't directly impact the server.

    If you want the user to submit to asstoticket.php, do so. You don't need javascript for that.

    If you need to set the session variable before that, which I can understand, use a separate page called with the ajax() code as I outlined.

    I can give you working demo files of the concept if you like.
    Last edited by jscheuer1; 06-10-2011 at 02:53 PM. Reason: add more detail
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #7
    Join Date
    Jun 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thanks i would be a great help..

  8. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    28,925
    Thanks
    43
    Thanked 3,190 Times in 3,154 Posts
    Blog Entries
    12

    Default

    Here's an archive of three files:

    Attachment 3932

    Unzip them to a folder on your PHP enabled server. Open posit.htm in the browser. Enter a value in the text input and click Go, then Check It. You will see the session variable has been set.

    The contents of the files are very simple. They show how to set the session variable from javascript. If you want a more complex page to evaluate the variable, do something with it and perhaps even do all kinds of other things, edit chkit.php, not mypost.php. You never see mypost.php anyway.

    The files of course can be renamed and/or moved around, as long as the names and/or paths to them are then updated in the code as need be.
    Last edited by jscheuer1; 06-13-2011 at 07:26 AM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

Bookmarks

Posting Permissions

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