通过ajax将值从javascript传递给sql

时间:2017-11-06 08:16:31

标签: javascript php jquery ajax

当我在php,javascript和ajax上传递变量时,我遇到了一些问题。

html - 当我更改所选值时,ajax将发布新值:

<select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onclick="fireAjax()" class="form-control" >
    <option value="0" disabled selected  hidden> -- select an option -- </option>
    <option value="PLINE">Phone Line Only</option>
    <option value="UNIFI">Unifi for New Registration</option>
    <option value="STREAMYX">Streamyx for New Registration</option>
    <option value="WEBE">Webe</option>
    <option value="DOME">Lease Line (DOME)</option>
</select>

ajax - 我通过javascript获取值并将其保存在var1中:

<script>
function fireAjax(){
    $.ajax({
        url: 'form.php',
        type: 'POST',
        data: {var1: document.getElementById('PACKAGE_ID').innerHTML },
        success: function(data) {
            console.log("success");
        }
    });
}

javascript函数 - 我想从ajax中取值var1,但是失败了:

<script>
$(function () {
var pricestore = [
    <?php
    $var1 = $_POST['var1']; // I cannot get the var1, please help me T.T
    $sqlpid=mysqli_query($conn, "select no from product where P_NAME = '$var1' ");

    //some function
    //.............
    ?>
];
});
</script>

3 个答案:

答案 0 :(得分:0)

onclick()更改为 onchange()

<select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onchange="fireAjax()" class="form-control" > //Here
<option value="0" disabled selected  hidden> -- select an option -- </option>
<option value="PLINE">Phone Line Only</option>
<option value="UNIFI">Unifi for New Registration</option>
<option value="STREAMYX">Streamyx for New Registration</option>
<option value="WEBE">Webe</option>
<option value="DOME">Lease Line (DOME)</option>

答案 1 :(得分:0)

尝试以下方法:

HTML:

  <select name="PACKAGE_CATEGORY" id="PACKAGE_CATEGORY" onchange="fireAjax()" class="form-control" >
    <option value="0" disabled selected  hidden> -- select an option -- </option>
    <option value="PLINE">Phone Line Only</option>
    <option value="UNIFI">Unifi for New Registration</option>
    <option value="STREAMYX">Streamyx for New Registration</option>
    <option value="WEBE">Webe</option>
    <option value="DOME">Lease Line (DOME)</option>
</select>

Javscript:

<script>
    function fireAjax(){
        $.ajax({
            url: 'form.php',
            type: 'POST',
            data: {var1: document.getElementById('PACKAGE_CATEGORY').value},
            success: function(data) {
                console.log("success");
            }
        });
    }

将onclick更改为onchange,更改了id,将innerHtml更改为value

答案 2 :(得分:0)

尝试将ajax调用更改为选择器的更改事件,

$('#PACKAGE_CATEGORY').change(function(){
    $.ajax({
        url: 'form.php',
        type: 'POST',
        data: {
            'var1': $(this).val() 
        },
        success: function(data) {
            console.log("success");
        }
    });
})