使用ajax将javascript变量传递给PHP,但会产生错误

使用ajax将javascript变量传递给PHP,但会产生错误,javascript,php,jquery,mysql,ajax,Javascript,Php,Jquery,Mysql,Ajax,我正在尝试使用Ajax将JavaScript变量传递到PHP脚本中,但由于它是未定义的索引,所以无法工作。这两个代码位于不同的文件中,但都可以在主页上访问 这是我的script.php <script> function get_child_options(){ var parentID = jQuery('#parent').val(); jQuery.ajax({ url: '/**/**/**/child_categories.php',

我正在尝试使用Ajax将JavaScript变量传递到PHP脚本中,但由于它是未定义的索引,所以无法工作。这两个代码位于不同的文件中,但都可以在主页上访问

这是我的script.php

<script>
function get_child_options(){
    var parentID = jQuery('#parent').val();
    jQuery.ajax({
        url: '/**/**/**/child_categories.php', 
        type: 'POST',
        data: {parentID : parentID},
        success: function(data){
            jQuery('#child').html(data);
        },
        error: function(){alert("Something Went Wrong with child options. ")},
    });
}
jQuery('select[name="parent"]').change(get_child_options);
</script>

函数get_child_options(){
var parentID=jQuery('#parent').val();
jQuery.ajax({
url:“/**/**/child_categories.php”,
键入:“POST”,
数据:{parentID:parentID},
成功:功能(数据){
jQuery('#child').html(数据);
},
错误:函数(){alert(“子选项出错。”)},
});
}
jQuery('select[name=“parent”]”)。更改(获取子选项);
这是我的php文件

<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/ **/core/init.php';             //Including database path stored in init.php

$parentID = (int)$_POST['parentID'];
$childQuery = "SELECT * FROM categories WHERE parent = '$parentID' ORDER BY category";

ob_start();
?>

<option value="">Select <strong>Child</strong> Category</option>
<?php while ($child = mysqli_fetch_assoc($childQuery)): ?>
    <option value="<?= $child['id']; ?>"><?= $child['category']; ?></option>

<?php endwhile; ?>
<?php
    echo ob_get_clean();
?>

在脚本中#parent是我使用jQuery传递给javascript的表单id

由于变量不可访问,PHP未运行查询

这是my products.php,这是发生这种情况的主要页面

    <?php
    require_once $_SERVER['DOCUMENT_ROOT'].'/Online Store/core/init.php';           //Including database path stored in init.php
    include 'includes/head.php';                                                    //Including header
    include 'includes/navigation.php';                                              //Including Navigation bar
    include 'includes/script.php';                                              

    if (isset($_GET['add'])) {
        $brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
        $parentQuery = $db->query("SELECT * FROM categories WHERE parent = 0 ORDER BY category");

?>      
    <h2 class="text-center">Add A New Product</h2><hr />
    <form action="products.php?add=1" method="post" enctype="multipart/form-data">
        <div class="form-group col-md-3">
            <label for="title">Title*:</label>
            <input type="text" class="form-control" id="title" name="title" value="<?= ((isset($_POST['title']))?sanitize($_POST['title']):''); ?>" placeholder="Add a title" />
        </div>
        <div class="form-group col-md-3">
            <label for="brand">Brand*: </label>
            <select class="form-control ">
                <option value="" <?= ((isset($_POST['brand']) && $_POST['brand'] == '')?' selected':''); ?> >Select Brand</option>
                <?php while($brand = mysqli_fetch_assoc($brandQuery)): ?>
                    <option value="<?= $brand['id']; ?>" <?= ((isset($_POST['brand']) && $_POST['brand'] == $brand['id'])?' selected':''); ?> ><?= $brand['brand'] ?></option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="form-group col-md-3">
            <label for="parent">Parent Category*: </label>
            <select class="form-control" id="parent" name="parent">
                <option value="" <?= ((isset($_POST['parent']) && $_POST['parent'] == '')?' select':''); ?> >Select <strong>Parent</strong> Category</option>
                <?php while($parent = mysqli_fetch_assoc($parentQuery)): ?>
                    <option value="<?= $parent['id']; ?>" <?= ((isset($_POST['parent']) && $_POST['parent'] == $parent['id'])?' select':''); ?> ><?= $parent['category']; ?></option>
                <?php endwhile; ?>  
            </select>

        </div>
        <div class="form-group col-md-3">
            <label for="child">Child Category*: </label>
            <select id="child" name="child" class="form-control"></select>
            <?php include $_SERVER['DOCUMENT_ROOT'].'/Online Store/admin/parsers/child_categories.php'; ?>
        </div>
        <div class="form-group col-md-3">
            <label for="price">Price*: </label>
            <input type="text" id="price" name="price" class="form-control" value="<?= ((isset($_POST['price']))?sanitize($_POST['price']):''); ?>" />

        </div>
        <div class="form-group col-md-3">
            <label for="list_price">List Price*: </label>
            <input type="text" id="list_price" name="list_price" class="form-control" value="<?= ((isset($_POST['list_price']))?sanitize($_POST['list_price']):''); ?>" />

        </div>
        <div class="form-group col-md-3">
            <label>Quantity & Sizes</label>
            <button class="btn btn-default btn-info form-control" onclick="jQuery('#sizesModal').modal('toggle'); return false;">Quantity & Sizes</button>
        </div>
        <div class="form-group col-md-3">
            <label for="sizes">Sizes & Quantity preview*: </label>
            <input type="text" name="sizes" id="sizes" class="form-control" value="<?= ((isset($_POST['sizes']))?$_POST['sizes']:''); ?>" readonly/>
        </div>
        <div class="form-group col-md-6">
            <label for="photo">Photo*: </label>
            <input type="file" name="photo" id="photo" class="form-control" />
        </div>
        <div class="form-group col-md-6">
            <label for="description">Description</label>
            <textarea name="description" id="description" class="form-control" rows="6" placeholder="Description" ><?= ((isset($_POST['description']))?sanitize($_POST['description']):''); ?></textarea>
        </div>
        <div class="form-group pull-right">
        <input type="submit" class="form-control btn btn-success" value="Add Product" />
        </div>
        <div class="clearfix"></div>
    </form>
<?php   
    }else{

    $sql = "SELECT * FROM products WHERE deleted = 0";
    $presults = $db->query($sql);
    $product = mysqli_fetch_assoc($presults);

    // Featured product
    if (isset($_GET['featured'])) {
        $id = (int)$_GET['id'];
        $featured = (int)$_GET['featured'];
        $featuredSql = "UPDATE `products` SET `featured` = '$featured' WHERE `products`.`id` = '$product[id]' ";
        $db->query($featuredSql);
        // header('Location: products.php');
    }
?>

<h2 class="text-center">Products</h2>
<a href="products.php?add=1" class="btn btn-success pull-right" id="add-product-btn">Add Product</a><div class="clearfix"></div>
<hr />

<table class="table table-bordered table-condensed table-striped">
    <thead>
        <th></th>
        <th>Product</th>
        <th>Price</th>
        <th>Category</th>
        <th>Featured</th>
        <th>Sold</th>
    </thead>
    <tbody>
        <?php 
            while($product = mysqli_fetch_assoc($presults)): 
                $childID = $product['categories'];
                $catSql = "SELECT * FROM categories WHERE id = '$childID'";
                $result = $db->query($catSql);
                $child = mysqli_fetch_assoc($result);
                $parentID = $child['parent'];
                $pSql = "SELECT * FROM categories WHERE id = '$parentID'"; 
                $presult = $db->query($pSql);
                $parent = mysqli_fetch_assoc($presult);
                $category = $parent['category'].'~'.$child['category'];
        ?>
            <tr>
                <td>
                    <a href="products.php?edit=<?= $product['id']; ?>" class="btn btn-xs btn-default"><span class= " glyphicon glyphicon-pencil"></span></a>
                    <a href="products.php?delete=<?= $product['id']; ?>" class="btn btn-xs btn-default"><span class= " glyphicon glyphicon-remove-sign"></span></a>

                </td>
                <td><?= $product['title']; ?></td>
                <td><?= money($product['price']) ?></td>
                <td><?= $category; ?></td>
                <td><a href="products.php?featured=<?= (($product['featured'] == 0)?'1':'0'); ?>&id =<?= $product['id']; ?>" class=" btn btn-sx btn-default">
                    <span class=" glyphicon glyphicon-<?= (($product['featured'] == 1)?'minus':'plus'); ?>"></span>

                </a>&nbsp <?= (($product['featured'] == 1)?'Featured':''); ?></td>
                <td>0</td>
            </tr>
        <?php endwhile; ?>  
    </tbody>
</table>

<?php
}
    include 'includes/footer.php';                                                  //Including footer

?>

添加新产品
标题*: 试试这个:

<script>
function get_child_options(){
    var parentID = $(this).val();
    jQuery.ajax({
        url: '/**/**/**/child_categories.php', 
        type: 'POST',
        data: {'parentID' : parentID},
        success: function(data){
            jQuery('#child').html(data);
        },
        error: function(){alert("Something Went Wrong with child options. ")},
    });
}
jQuery('select[name="parent"]').change(get_child_options);
</script>

函数get_child_options(){
var parentID=$(this.val();
jQuery.ajax({
url:“/**/**/child_categories.php”,
键入:“POST”,
数据:{'parentID':parentID},
成功:功能(数据){
jQuery('#child').html(数据);
},
错误:函数(){alert(“子选项出错。”)},
});
}
jQuery('select[name=“parent”]”)。更改(获取子选项);

通过$(this)获取值,并在parentID
data:{'parentID':parentID}周围加上单引号,

你确定ajax已经通过了吗?你可以共享html来显示id为Parents的元素吗?你使用的是核心php还是框架??#ParentID必须是select而不是form id可以共享html以获取更多信息我已经更新了html页面“undefined index”消息的全文是什么?没有发生任何事情。我完全按照你说的做了。仍然存在错误。