在下拉列表更改时将JavaScript变量传递给PHP

时间:2015-06-02 22:10:24

标签: javascript php ajax post get

我正在尝试根据下拉框中的值更改来更改div中的文本。使用PHP从MySQL填充下拉框值。我在页面加载时加载下拉框。

<script>

$(document).ready(function() {
$('#products').change(function(){

var idval=$('#products').val();
$.ajax
        (   {
                type: "post",
                url: "my.php",
                data: {winner_id:idval}, 
                success: function(response)
                { alert("The winner was passed!")},
            }
        );

 <?php 
require_once 'config.php';


$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is  :".$row["prod_time"];

 ?> 
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );

   });

  });

</script>

我没有得到结果。

让我知道如何将JavaScript值idval分配给PHP变量$iid值。

1 个答案:

答案 0 :(得分:0)

//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample

<script>

  $(document).ready(function() {
  $('#products').change(function(){

 var idval=$('#products').val();
$.ajax
    (   {
            type: "post",
            url: "my.php",
            data: {winner_id:idval}, 
            success: function(response){
              for (var i = 0; i < response.length; i++) {
                  $("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
              }
            },
        }
    );

</script>