2016-04-13 89 views
0

我想用一个输入文本“连接”一个选择,而不刷新页面选择平变化更新PHP价值

这是我的例子

<select name="name_select" id="my_select"> 
    <option value="1">first</option> 
    <option value="2">first</option> 
    <option value="3">first</option> 
</select> 

<?php ...query(SELECT name FROM table WHERE id = value) ?> 

然后在变量$名称有值从数据库

<input type="text" value="<?php echo $name; ?>" /> 

我想我必须使用jQuery的岗位/得到,但如何更新只是我需要检查分贝变种?

+7

AJAX是为这个 – Thamilan

+0

你可以用AJAX调用实现它,因为AJAX不会刷新页面。问题中添加Ajax标签。 – RJParikh

回答

3

像Thamizhan说,在评论,你需要使用AJAX。

下面是一个简单的例子:

HTML(index.html的)

<select name="name_select" id="my_select"> 
    <option value="1">first</option> 
    <option value="2">first</option> 
    <option value="3">first</option> 
</select> 

JS

$('#my_select').on('change', function() { 
    var selectData = $(this).val(); 
    $.ajax({ 
     type: "POST", 
     url: "custom.php", 
     data: {'selectData': selectData }, 
     success: function (json) { 
      // do things 
     } 
    }); 
} 

PHP(custom.php)

if (isset($_POST['selectData'])) { 
    var_dump($_POST['selectData']); // $_POST['selectData'] is the selected value 
    // query here 
    // and you can return the result if you want to do some things cool ;) 
} 
0
$("#my_select").on("change", function() { 
    $.ajax({ 
     url: "phpfile.php", 
     method: 'POST', 
     data: {val: $(this).val()}, 
     success: function (data) { 
      $("[type='text']").val(data); 

     } 
    }); 
}); 

在phpfile.php

include("db.php"); 

// ... your code ... 

// execute sql(SELECT name FROM table WHERE id = value) and return value. 
0

请清除一件事,为什么你需要sql查询这里。

<option value="1">first</option> 

第一个是名字,第一个是选项。那么我们可以将第一个或第一个放入输入框,而不使用sql和ajax。

只使用jQuery的这个

$(document).ready(function(){ 
    $("#my_select").change(function(){ 

    var thisval = $(this).val();  
    $("input").val(thisval); 
    }); 
});