来自AJAX的值插入PHP

时间:2019-05-02 22:45:39

标签: javascript php mysql json ajax

我创建一个示例页面,其中包含两个字段:“汽车生产年份”和“特定年份生产的汽车品牌”。 使用AJAX,我想将ID #year中的值发送到文件“ brand_year_get.php”以在sql查询中使用此值。然后此文件将通过JSON从数据库获取的值发送到表单。 如果我在SELECT中输入特定值,例如'5',然后从表格中显示给定年份生产的汽车的品牌。但是,如果我在查询中引入变量$ year3(应使用POST方法从AJAX中获取该变量),它将无法正常工作……;(我不知道自己在做什么错了:( 请帮我! ;)

form.php

<form>
<select id='year'>
Year of car production:
<?php
require_once 'connect.php';
$con=new mysqli($host, $db_user, $db_password, $db_name);
$get1 = $con->query("SELECT * FROM kom_car_year");
        while($year1=mysqli_fetch_assoc($get1))
        {echo '<option value="'.$year1['id_kom_car_year_prod'].' ">'.$year1['year_prod'].'</option>';}
?>
</select>
</form>

<select id='brand'>
</select>

<script>
$(document).ready(function(){

     $('#year').click(function() {

        var year2 = $('#year').val();

         $.ajax({
             type:"POST",
             url:"brand_year_get.php",
             data: {key_ajax:year2},

                 success:function() {

                    alert("Sent"); 

                 },

                 error: function(err) {
                     alert( "Error");
                     console.log(err);
                 }
         });

     });

$('#year').click(function(){

    $.ajax({
        type:"GET",
        url:"brand_year_get.php",
        contentType:"application/json; charset=utf-8", 
        dataType:'json',

        success: function(json) {

           for (var key in json)
                    {
                        var line = json[key];    
                        var id_brand = line[0];
                        var brand = line[1];

                        $("<option value="+id_brand+">"+brand+"</option>")
                        .appendTo('#brand')
                        .append("<hr>")
                    }  

        },
                    error: function(err) {
                    alert( "Error");
                    console.log(err);
                }

        });

    });
});
</script>

brand_year_get.php

<?php

header('Content-type: application/json');

$year3=$_POST['key_ajax'];

    require_once 'connect.php';
    $con=new mysqli($host, $db_user, $db_password, $db_name);
    $con->set_charset("utf8");

    if (mysqli_connect_errno())
    {
    echo "Not connected to the database " . mysqli_connect_error();
    }
    else
    {
        $get1=$con->query("SELECT kom_car_brand_year.id_brand, kom_car_brand.brand FROM kom_car_brand_year INNER JOIN kom_car_brand ON (kom_car_brand_year.id_brand=kom_car_brand.id_brand ) WHERE id_kom_car_year='$year3'");
        $get1_data = array();

            while ($line = mysqli_fetch_row($get1)) 
            {
              $get1_data[] = $line;
            }
            echo json_encode($get1_data);
        }
?>

0 个答案:

没有答案