Viewed   70 times

Is there any way to pass a javascript variable to a php function or simply assign a js variable to a php variable....???

test("asdas"); I need to update "asdas" to a dynamic value, i.e of the form,

 Answers

2

You can pass value from js to PHP using ajax request or add js value to URL and then reload page.

Variant #1 (using ajax):

JS side (jquery)

var js_var = 'hello';
$.ajax({
   type: "POST",
   url: "some.php",
   data: "js_var="+js_var,
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

PHP side

$js_var = isset($_POST['js_var']) ? $_POST['js_var'] : '';

Variant #2 (with page reload):

JS side

<script type="text/javascript">
<!--
var js_var = 'hello';
window.location = "http://www.yoursite.com/?js_var="+js_var;
//-->
</script>

PHP side

$js_var = isset($_GET['js_var']) ? $_GET['js_var'] : '';

Saturday, August 20, 2022
4

As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post

Maybe the most easiest approach for you is something like this

function myJavascriptFunction() { 
  var javascriptVariable = "John";
  window.location.href = "myphpfile.php?name=" + javascriptVariable; 
}

On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Regards

Friday, September 30, 2022
4

You cannot pass variable values from the current page JavaScript code to the current page PHP code... PHP code runs at the server side, and it doesn't know anything about what is going on on the client side.

You need to pass variables to PHP code from the HTML form using another mechanism, such as submitting the form using the GET or POST methods.

<DOCTYPE html>
<html>
  <head>
    <title>My Test Form</title>
  </head>

  <body>
    <form method="POST">
      <p>Please, choose the salary id to proceed result:</p>
      <p>
        <label for="salarieids">SalarieID:</label>
        <?php
          $query = "SELECT * FROM salarie";
          $result = mysql_query($query);
          if ($result) :
        ?>
        <select id="salarieids" name="salarieid">
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<option value="', $row['salaried'], '">', $row['salaried'], '</option>'; //between <option></option> tags you can output something more human-friendly (like $row['name'], if table "salaried" have one)
            }
          ?>
        </select>
        <?php endif ?>
      </p>
      <p>
        <input type="submit" value="Sumbit my choice"/>
      </p>
    </form>

    <?php if isset($_POST['salaried']) : ?>
      <?php
        $query = "SELECT * FROM salarie WHERE salarieid = " . $_POST['salarieid'];
        $result = mysql_query($query);
        if ($result) :
      ?>
        <table>
          <?php
            while ($row = mysql_fetch_assoc($result)) {
              echo '<tr>';
              echo '<td>', $row['salaried'], '</td><td>', $row['bla-bla-bla'], '</td>' ...; // and others
              echo '</tr>';
            }
          ?>
        </table>
      <?php endif?>
    <?php endif ?>
  </body>
</html>
Saturday, December 10, 2022
1

PHP and javascript don't work like that.

PHP is a server-side language. While javascript is a clientside language.

There are still ways of passing data from the client-window to your server, via ajax, query parameters, cookies... But none will work in the same page.

Give us a clearer image on what you are trying to achieve and we will gladly help.

UPDATE

JS

<script type="text/javascript">  
    document.cookie = 'name=Khez' ;  
</script>  

PHP

<?php  
    var_dump($_COOKIE['name']);  
?>  
Sunday, October 23, 2022
 
perl
 
1

Have a look at jstree. I think this is what you want. (I'm done it using jstree). Jstree is a javascript library that can be used control to render tree structures like HTML lists (<ul>, <ol>) or json or xml as controllable tree with '+' to open and close a folder like you wished.

Of course jstree is just the javascript part. You'll have to format the outputs of your getDirectoryListing() to one of the formats jstree supports. This are currently

  • Json
  • XMl
  • Html

Here comes a basic example. When finiehd it will look like this:

You can play around with the tree open and close nodes.

I've changed your directory listing function to a one that produces JSON for jstree. Its actually derived from this SO post to get things quick working. Thanks! :) Here is the php. Place it in a folder in your webserver and name it tree.php

<?php

header('Content-Type: application/json');
echo json_encode(dir_to_jstree_array(__DIR__));

function dir_to_jstree_array($dir, $order = "a", $ext = array()) {

    if(empty($ext)) {
        $ext = array (
            "jpg", "gif", "jpeg", "png", "doc", "xls", "pdf", "tif"
        );
    }

    $listDir = array(
        'data' => basename($dir),
        'attr' => array (
            'rel' => 'folder'
        ),
        'metadata' => array (
            'id' => $dir
        ),
        'children' => array()
    );

    $files = array();
    $dirs = array();

    if($handler = opendir($dir))
    {
        while (($sub = readdir($handler)) !== FALSE)
        {
            if ($sub != "." && $sub != "..")
            {
                if(is_file($dir."/".$sub))
                {
                    $extension = pathinfo($dir."/".$sub, PATHINFO_EXTENSION);
                    if(in_array($extension, $ext)) {
                        $files []= $sub;
                    }
                }elseif(is_dir($dir."/".$sub))
                {
                    $dirs []= $dir."/".$sub;
                }
            }
        }

        if($order === "a") {
            asort($dirs);
        } else {
            arsort($dirs);
        }

        foreach($dirs as $d) {
            $listDir['children'][]= dir_to_jstree_array($d);
        }

        if($order === "a") {
            asort($files);
        } else {
            arsort($files);
        }

        foreach($files as $file) {
            $listDir['children'][]= $file;
        }

        closedir($handler);
    }
    return $listDir;
}

Here comes the basic HTML and javascript. Give it a proper name and place it beside the tree.php. I'm using the json_data plugin of jstree together with ajax. Also I'm using the types plugin to render different types of icons for folders and files. (It would be possible to have a custom icon for each filetype too, if you want). You'll have to place a proper folder.png and image.png beside the html file.

<html>
  <head>
    <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="jstree-v.pre1.0/jquery.jstree.js"></script>
    <script type="text/javascript">

        $(function() {
          $('#dirtree').jstree({
            plugins : ["json_data", "themes", "types"],

            json_data : {
              ajax : {
                'url' : 'tree.php'
              }
            },

            'types': {
              'types' : {

                'folder' : {
                  'icon' : {
                    'image' : 'folder.png'
                  }
                },

                'default' : {
                  'icon' : {
                    'image' : 'image.png'
                  },
                }
              }
            }
          });
        }); 

    </script>
 </head>
 <body>
   <div id="dirtree"></div>
 </body>
</html>

Thats it! :) Note that you have many configuration options, styling options and plugins to jstree. You'll of course extend my example.

Please refer to the link above to the jstree project page for information about installation of jstree and the documentation.

Friday, October 21, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :