简体   繁体   English

通过PHP将Javascript变量的值传递给MySQL

[英]Pass value of Javascript variable to MySQL through PHP

I want to pass area name selected from drop down menu to query of MySQL through PHP. 我想将通过下拉菜单选择的区域名称通过PHP传递给MySQL查询。 I retrieved name in JavaScript but I am unable to store value from JavaScript to PHP. 我在JavaScript中检索了名称,但无法将值从JavaScript存储到PHP。 My Code is As follows 我的代码如下

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <script>
        function getIndex()
        {
            var x=document.getElementById("cmbArea").selectedIndex;
            var y=document.getElementById("cmbArea").options

            var z= y[x].text;
            alert(z); 
        }
    </script>
</head>
<body>
    <form name ="form1" action="Demo1.php" method="post">
    <select id="cmbArea" name="cmbArea">
    <?php
    include 'Connect.php';
    $query = "SELECT varAreaName FROM tbArea" ;
    $result = mysql_query($query);       
    while($row = mysql_fetch_assoc( $result )) { 
        echo '<option value="'.$row['varAreaName'].'">' . $row['varAreaName'] . '</option>';   
    }

    ?>
    </select>
    </form>
    <input type="Button" onclick="getIndex()" value="Alert index of selected option">

   </body>
   </html>

You need to post your form. 您需要发布表格。 The value will be available in $_POST['cmbArea'] . 该值将在$_POST['cmbArea']可用。

If I am understanding you correctly I would use AJAX in this case. 如果我对您的理解正确,在这种情况下,我将使用AJAX。 Something like this: http://openenergymonitor.org/emon/node/107 像这样的东西: http : //openenergymonitor.org/emon/node/107

Yes, you can not 'store' value from javascript to PHP, as javascript is in client-side(literally in your Browser-side), not in the server-side. 是的,您不能将javascript中的值“存储”到PHP,因为javascript在客户端(实际上是在浏览器端),而不是在服务器端。

You need to post the data using ajax(Jquery ajax may be), and post them in JSON format. 您需要使用ajax(可能是jquery ajax)发布数据,并以JSON格式发布它们。 Check this thread.. 检查此线程。

PHP will run on server and then javascript will be run on the browser. PHP将在服务器上运行,然后javascript将在浏览器上运行。 So you cannot do both in the same page, as you try. 因此,您不能像尝试那样在同一页面上同时执行这两项操作。

I think the best way is to submit the form, and read the value there using PHP. 我认为最好的方法是提交表单,并使用PHP读取其中的值。 There you can execute your query. 您可以在那里执行查询。

If you don't want to submit you can check AJAX which will send an asynchronous server side request, without refreshing the webpage. 如果您不想提交,则可以检查AJAX,它将在不刷新网页的情况下发送异步服务器端请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM