Jump to content

Why checking existence of a session variable always return false


adrianmak
 Share

Recommended Posts

here is my snippet of code

        if(!empty($session->cart_item)) {
                        // session variable existed and to update session variable content

                       
        } else {
           // add new session variable
           $session->set("cart_item", $itemArray);
       }

I found that the if statement always false.

Should I use the wrong way for checking an existence of session variable ?

Link to comment
Share on other sites

I tried to use isset in place of !empty(), but it still not working.

My scenario is adding a product to cart thru ajax

here is my code server side php ajax for adding item into session variable

<?php

// ProcessWire bootstrap
include('./index.php');

$a = '';
if(wire('config')->ajax) {
    $action = $_POST['action'];
    $product_id = $_POST['product_id'];
    $quantity = $_POST['quantity'];

    if(!empty($action)) {
        switch($action) {
            case "add":
                if(!empty($quantity)) {
                    $product = $pages->get($product_id);
                    $itemArray = array($product->id =>
                                    array('name' => $product->title,
                                            'id' => $product->id,
                                            'quantity' => $quantity,
                                            'price' => $product->price
                                    )
                    );

                    if(isset($session->cart_item)) {
                        // session variable existed

                        if(in_array($itemArray, $session->cart_item)) {
                            foreach($session->cart_item as $key => $value) {
                                if($itemArray == $key)
                                    $session->cart_item[$key]["quantity"] = $quantity;
                            }
                        } else {
                            $session->cart_item = array_merge($session->cart_item, $itemArray);
                            $a = "NEW";
                        }

                        $a = "NEW item added";

                        //$session->set("cart_item", $itemArray);
                    } else {
                        $session->set("cart_item", $itemArray);
                    }
                }
                break;
            case "remove":
                break;
            break;
        }
    echo "OK" . " " . $a;
    }

} else {
    echo "cannot execute the script directly.";
}


The js script

//$(document).ready(function () {

function cartAction(action, product_id) {
    var queryString = "";

    if(action != "") {
        switch(action) {
            case "add":
                queryString = 'action='+action+'&product_id='+product_id+'&quantity='+$("#quantity").val();
                break;
            case "remove":
                queryString = 'action='+action+'&product_id='+product_id;
                break;
            break;
        }
    }

    console.log(queryString);

    jQuery.ajax({
        url: "/cart_ajax.php",
        data: queryString,
        type: "POST",
        success: function(data) {
            console.log(data);
        }
    });
}

//})

the product detail template

<?php

$content = "";
$out = "";
$header_image = '';
$js = '';

$js .= "<script src='{$config->urls->templates}assets/js/cart.js'></script>";

// render product details
$out = wireRenderFile("partial/product-details-tpl", array('product'=>$page));

$content .= $out;

product detail render template

<?php


$out = "";

$out .= "<div class='product-detail'>";
$out .= "<form class='formCart'>";
$out .= "<div id='product' class='row list-group'>";
$out .= "<div class='col-xs-5 col-lg-5'>";
$out .= "<div class='thumbnail'>";
$out .= "<img class='group list-group-image' src='{$product->product_img->url}' width='100%' alt='' />";
$out .= "</div>";
$out .= "</div>";
$out .= "<div class='col-xs-7 col-lg-7'>";
$out .= "<input type='hidden' name='product-id' value='{$product->id}' />";
$out .= "<div class='product-title'><h2>{$product->title}</h2></div>";
$out .= "<div class='product-price'>HKD {$product->price}</div>";
$out .= "<div class='product-desc'>{$product->body}</div>";
$out .= "<div class='product-quantity'>";
$out .= "<label for='quantity'>Quantity:</label>";
$out .= "<select class='form-control' id='quantity' name='quantity'>";
$out .= "<option value='1' selected>1</option>";
$out .= "<option value='2'>2</option>";
$out .= "<option value='3'>3</option>";
$out .= "<option value='4'>4</option>";
$out .= "<option value='5'>5</option>";
$out .= "<option value='6'>6</option>";
$out .= "<option value='7'>7</option>";
$out .= "<option value='8'>8</option>";
$out .= "<option value='9'>9</option>";
$out .= "<option value='10'>10</option>";
$out .= "</select>";
$out .= "</div>";
$out .= "<div class='add-to-cart'>";
$out .= "<input class='btn btn-primary btn-lg' name='submit' type='button' value='Add to cart' onclick=\"cartAction('add', '{$page->id}')\" />";
$out .= "</div>";
$out .= "</div>";
$out .= "</div>";
$out .= "</form>";
$out .= "</div>";

echo $out;

Link to comment
Share on other sites

I tried to put folllowing code at the end of product template file

$content .= count($session->cart_item);


if(isset($session->cart_item)) {
    $content .= "session existed";
} else  {
    $content .= "session non-existed";
}

count shown 1 but the if statement return false. "sessoion non-existed" is appended

Link to comment
Share on other sites

How to update an existing session variable ?

A session variable cart_item has such a array structure

Array ( [10] => Array ( [name] => product-10 [id] => 10 [quantity] => 10 [price] => 250 ) ) 

For testing and debugging, I tried to update the quantity manual

$session->cart_item[10]['quantity'] = 20;

Then, I printed again the cart_item session variable, it's quantity is still 10

Link to comment
Share on other sites

And (again) $session->cart_item is not a variable, it just does return or receive one. You need to update the array separately.

$cart_item = $session->cart_item;
$cart_item[10]['quantity'] = 20;
$session->cart_item = $cart_item:
  • Like 2
Link to comment
Share on other sites

So this is sufficient, as in most cases in PW like fields. No isset() or empty() etc.

if($session->cart_item){
    .... exists or is populated
} else {
    .... doesn't exists or is empty
}

You can also write, as always in PW

$session->get("cart_item");

You can also use namespaced session

$session->seFor("myshop", "cart_item", $cart_item);

and get it with

$cart_item = $session->getFor("myshop", "cart_item");

BTW what happens if hack your code and enter a "template=user, id=40, check_access=0" into your "product_id" POST?

  • Like 7
Link to comment
Share on other sites

Should I use in_array() to checks if a value exists in $session->cart_item ?

The array structure like

Array
(
    [1106] => Array
        (
            [name] => LanguagesPageFieldValue Object
                (
                    [data:protected] => Array
                        (
                            [1013] => 測試產品2
                            [1015] => 
                            [1016] => 
                        )

                    [defaultLanguagePageID:protected] => 1013
                    [field:protected] => Field Object
                        (
                            [settings:protected] => Array
                                (
                                    [id] => 1
                                    [type] => FieldtypePageTitleLanguage Object
                                        (
                                            [allowTextFormatters:FieldtypeText:private] => 1
                                            [data:protected] => Array
                                                (
                                                )

                                            [useFuel:protected] => 1
                                            [className:Wire:private] => FieldtypePageTitleLanguage
                                            [classNameOptions:Wire:private] => Array
                                                (
                                                )

                                            [localHooks:protected] => Array
                                                (
                                                )

                                            [trackChanges:Wire:private] => 0
                                            [changes:Wire:private] => Array
                                                (
                                                )

                                            [_notices:protected] => Array
                                                (
                                                    [errors] => 
                                                    [warnings] => 
                                                    [messages] => 
                                                )

                                        )

                                    [flags] => 13
                                    [name] => title
                                    [label] => Title
                                )

                            [prevTable:protected] => 
                            [prevFieldtype:protected] => 
                            [trackGets:protected] => 
                            [viewRoles:protected] => Array
                                (
                                )

                            [editRoles:protected] => Array
                                (
                                )

                            [data:protected] => Array
                                (
                                    [required] => 1
                                    [textformatters] => Array
                                        (
                                            [0] => TextformatterEntities
                                        )

                                    [size] => 0
                                    [maxlength] => 255
                                )

                            [useFuel:protected] => 1
                            [className:Wire:private] => 
                            [classNameOptions:Wire:private] => Array
                                (
                                )

                            [localHooks:protected] => Array
                                (
                                )

                            [trackChanges:Wire:private] => 2
                            [changes:Wire:private] => Array
                                (
                                )

                            [_notices:protected] => Array
                                (
                                    [errors] => 
                                    [warnings] => 
                                    [messages] => 
                                )

                        )

                    [useFuel:protected] => 1
                    [className:Wire:private] => 
                    [classNameOptions:Wire:private] => Array
                        (
                        )

                    [localHooks:protected] => Array
                        (
                        )

                    [trackChanges:Wire:private] => 2
                    [changes:Wire:private] => Array
                        (
                        )

                    [_notices:protected] => Array
                        (
                            [errors] => 
                            [warnings] => 
                            [messages] => 
                        )

                )

            [id] => 1106
            [quantity] => 1
            [price] => 265
        )

)

My code for checking if an item exists in cart item

$cart_item = $session->cart_item;
if(in_array($itemArray[$product->id], $cart_item)) {
   // do something                               
  $a = "update existing product item in cart_item.";
                        
} else {
   // do something else
   $a = "Add product item into cart.";
}

I  always return false. ie no match

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...