dongna2498
2016-09-29 20:14
浏览 38
已采纳

将“值”从表单中的选择传递到具有javascript问题的php变量

I'm trying to pass a value of a option in a select from my HTML form to a PHP variable through Javascript

<script type="text/javascript">
function changeDir(ID){
    var dir = document.getElementById(ID).value;
    //For debuging purposes i've used an alert to show the value of dir on screen
    //alert (dir);
    //At this point of the function I want to assign the value of "dir" to the variable $folder
    }
</script>

there's my .php with html

<SELECT name="course" ID="course" onchange='changeDir("course")' >
        <OPTION value="artes>'">artes</OPTION>
        <OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php $folder= ...?>

I'm using this with a php upload lib, all working at the same file. If anyone can explain me how to assign the value of the option to a php var will be great.

Thanks and Regards.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douyiqi9640 2016-09-29 21:15
    已采纳

    You can choose 2 different ways. First is AJAX, second is to redirect the page and GET the value of the <select> element.

    HTML:

    <SELECT name="course" ID="course" onchange='changeDir("course")' >
       <OPTION value="artes>'">artes</OPTION>
       <OPTION value="ingles">inglés</OPTION>
    </SELECT>
    

    JAVA:

    <script type="text/javascript">
    function changeDir(ID){
    var dir = $("course").val();
    $.post("php_file.php",
        {
          posted_dir: dir
        },
        function(data){
            $("id_of_result_elemnt").html(data);
        });
        }
    </script
    

    PHP:

    <?php
    $folder=$_POST['posted_dir'];
    echo "This text will be display in the element with id_of_result_elemnt ID";
    ?>
    

    Other method is redirect

    HTML+PHP:

    <SELECT name="course" ID="course" onchange='changeDir("course")' >
            <OPTION value="artes>'">artes</OPTION>
            <OPTION value="ingles">inglés</OPTION>
    </SELECT>
    <?php if (iset($_GET['folder']))
     {$_GET['folder']=$folder;}...?>
    

    JAVA:

    <script type="text/javascript">
    function changeDir(ID){
        var dir = document.getElementById(ID).value;
        window.location = "http://example.com/myphp?folder=" + dir;
        }
    </script>
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douliaopan1419 2016-09-29 20:27

    The fact is that you can't. They both live in different parts of your page. While you can write them in the same file, all PHP code is processed in the server side and Javascript is not able to see anything from the client side.

    What you could do is whether pass it as a AJAX request in order to get back some information to show to the user or make the <select> refresh the page when user changes the option by submitting the form, so you don't lose the "state" of your form, and then verify in your php block if there's any option selected.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题