使用ajax将javascript变量传递给PHP,但它给出了错误

时间:2016-03-31 02:18:14

标签: 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', 
        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>

这是我的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没有运行查询。

这是我的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

?>

还有其他办法吗?我想要做的是当用户选择父类别时我希望按照父类别安排子类别。

1 个答案:

答案 0 :(得分:0)

试试这个:

<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>

通过$(this)获取值并在parentID data: {'parentID' : parentID},附近放置单引号