使用jQueryAJAX向PHP脚本传递数据


Passing data using jQuery AJAX to PHP script

HTML、AJAX和PHP包含在下面。在引入AJAX之前,所有功能(表单标记和PHP处理从下面的HTML中删除的值)。

下拉列表(类别)是从MySQL查询中填充的。当用户选择一个选项时,我想通过ajax将ID传递给PHP脚本(index.PHP),以运行MySQL查询来填充另一个下拉列表(子类别)。

Chrome控制台日志表明ajax正确地传递了ID。

Firebug还显示它正在传递,并且URL是正确的(index.php?business_category_id=ajax传递的值)。如果正在传递GET变量,而我的PHP脚本正在查找它,为什么脚本没有响应?为什么它没有收到价值?我无法回音,所以我知道它没有收到。

ajax脚本位于js/script.js中,index.php(我的控制器)位于根目录中,带有html(buy-a-biz.php)的页面位于根目录并包含在php脚本中(见下文)。

如果有人能帮忙,我将不胜感激。我是使用jQueryajax的新手。

HTML。

<select name="category" id="business-category">
    <option value="all_categories">Select category</option>
    <?php foreach ($categories as $category): ?>
        <option value="<?php htmlout($category['id']); ?>"><?php htmlout($category['name']); ?></option>
    <?php endforeach; ?>
</select> 

AJAX。我还试用了$.get和$.post。

$(document).ready(function(){
    $("#business-category").change(function(){
        var category_id = $(this).val();
        console.log(category_id);
        $.ajax({
            type: 'GET',
            url: 'index.php',
            data: { business_category_id: category_id },
            success: function(category_id){
                $("#result").html(category_id + ' submitted successfully!');
            }
        });
    });
});

PHP。

if(isset($_GET['business_category_id'])){ 
    $category_id = htmlspecialchars($_GET['business_category_id']);
    include 'includes/dbconnect.php';
    try {
        $sql = "SELECT * FROM sub_category
                WHERE category_id = :category_id";
        $s = $db->prepare($sql);
        $s->bindValue(":category_id", $category_id);
        $s->execute();
        while($row = $s->fetch(PDO::FETCH_ASSOC)){
            $sub_categories[] = array(
                'id' => $row['id'],
                'category_id' => $row['category_id'],
                'name' => $row['name']
            );
        }
        $sql2 = "SELECT * FROM category";
        $s2 = $db->prepare($sql2);
        $s2->execute();
        while($row  = $s2->fetch(PDO::FETCH_ASSOC)){
            $categories[] = array(
                'id' => $row['id'],
                'name' => $row['name'],
            );
        }   
    } 
    catch (PDOException $e) {
        $errMsg = "Error fetching data" . $e->getMessage();
        include 'error.html.php';
        exit();
    }
    include 'buy-a-biz.php';
    exit();
}

您正在将done回调传递给$.ajax。您应该将此回调命名为success

$.ajax({
    type: 'GET',
    url: 'index.php',
    data: { business_category_id: category_id },
    success: function(category_id){
            $("#result").html(category_id + ' submitted successfully!');
        }
    });

或者对$.ajax:返回的promise调用done

$.ajax({
    type: 'GET',
    url: 'index.php',
    data: { business_category_id: category_id },
}).done(function(category_id) { 
    $("#result").html(category_id + ' submitted successfully!'); 
});