简体   繁体   中英

Calling PHP Variable from another file without the use of Session or Include

so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).

In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).

Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).

Header.php:

<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
   total: <?php echo $pages; ?>,
   page: 1,
   maxVisible: 5
}).on("page", function(e, num){
    e.preventDefault();
    $("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
    $("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>

Pagination.php

<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT,                   FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of   invalid page number
}else{
$page_number = 1;
}

echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);

//Limit our results within a specified range. 
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");

//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
    <th class="producthead" colspan="3"><a href="product.php?id='.$row["ProductID"].'">'.$row["ProductName"].'</a></th>
</tr>
<tr>
    <td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
    <td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
    <td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
    <td class="productfoot" colspan="3">5/5 Stars - <a href="review.php?id='.$row["ProductID"].'">Write A Review</a></td>
</tr>
</table><br />
';
}
echo '</ul>';

?>

Index.php

<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
    $results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
    $get_total_rows = mysqli_fetch_array($results);
    $pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>

        <div class="contentboxcontainer">
            <div class="centercontentbox">
        <div class="halfcontentboxcontainer">
            <div class="halfcontentbox">
                <div class="contenthead">Deals</div>
                <div class="content">
                    <div class="contentcontainer">
Test
                    </div>
                </div>
            </div>
        </div>
                <div class="halfimgcontentboxl">
                <img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
                </div>
            </div>
        </div>
        <div class="contentboxcontainer">
            <div id="contentbox">
                <div class="contenthead">Products</div>
                <div class="content">

                    <div id="results"></div>

                    <div class="pageswrap"><div class="pagination"></div>    <div style="clear:both;"></div></div>

                </div>
            </div>
        </div>

<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>

Send the category id as a post variable in the load command.

var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});

For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.

In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.

pagination.php

<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');

if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
    $category = 'AMD';
}

I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).

I can now call my variable in a mysql query on pagination.php

FROM products WHERE SubCategory2 = '".$category."'

Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM