( sorry for my english )
I have a little problem.
I want to store at session a shop-bascket, so I created the php/classes/bascket.php
:
class Product
{
private $id;
private $quantity;
function __construct(int $id, int $q)
{
$this->id = $id;
$this->quantity = $q;
}
...
}
class Bascket
{
private $products = array();
/* for testing */
function __construct()
{
$this->products[] = new Product(26, 1006);
}
function add(int $id, int $quantity)
{
...
}
function delete(int $id, int $quantity)
{
...
}
function __get($field) {
return $this->$field;
}
}
And I use this class on session anywhere I want:
include "php/classes/bascket.php"; (*or another correct path*)
session_start();
if(!isset($_SESSION["bascket"])) {
$_SESSION["bascket"] = serialize(new Bascket());
}
$bascket = unserialize($_SESSION["bascket"]);
Because I want to show the bascket on pressing a button, I made an ajax which do the following thing:
function display_bascket() {
$.ajax({
url: 'php/take_bascket.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(bascket){
//bascket = JSON.parse(bascket);
//bascket = jQuery.parseJSON(bascket);
$("#content").html(bascket);
}
});
}
And I tried a lot to can display the correct thing in take_bascket.php
to receive a good array, or a json in ajax.
<?php
session_start();
include "classes/bascket.php";
if(!isset($_SESSION["bascket"])) {
$_SESSION["bascket"] = serialize(new Bascket());
}
// I tried many variants:
var_dump($_SESSION["bascket"]);
/*
* output:
* string(116) "O:3:"Bascket":1:{s:12:"Bascketproducts";a:1:{i:0;O:6:"Product":2:{s:10:"Productid";i:26;s:17:"Productquantity";i:1006;}}}"
*
* and I don't know how to handled it in ajax to get the products array
*/
var_dump(unserialize($_SESSION["bascket"]));
/*
* output:
* object(Bascket)#1 (1) { ["products":"Bascket":private]=> array(1) { [0]=> object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) } } }
*
* and I don't know how to handled it in ajax to get the products array
*/
var_dump(json_encode($_SESSION["bascket"]));
/*
* output:
* string(158) ""O:3:\"Cos\":1:{s:12:\"\u0000Cos\u0000products\";a:1:{i:0;O:6:\"Product\":2:{s:10:\"\u0000Product\u0000id\";i:26;s:17:\"\u0000Product\u0000quantity\";i:1006;}}}""
*
* and I don't know how to handled it in ajax to get the products array
*/
var_dump(((unserialize($_SESSION["bascket"]))->products));
/*
* output:
* array(1) { [0]=> object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) } }
*
* and I don't know how to handled it in ajax to get the products array
*/
var_dump(((unserialize($_SESSION["bascket"]))->products[0]));
/*
* output:
* object(Product)#2 (2) { ["id":"Product":private]=> int(26) ["quantity":"Product":private]=> int(1006) }
*
* and I don't know how to handled it in ajax to get the products array
*/
As you can see I also tried different ways of manipulate the output in ajax. But or it is a string and I can't convert it in array. Or I can't make it json, etc.
Please, can you try find a complete solution? I mean for take_bascket.php, but also for what I have to do in display_bascket() in js.
thank you in advance
I did as someone said in a post:
php/classes/bascket.php
<?php
class Product
{
private $id;
private $quantity;
function __construct(int $id, int $q)
{
$this->id = $id;
$this->quantity = $q;
}
function decrease(int $value)
{
...
}
function increase(int $value) {
...
}
public function toArray(){
return [
'id' => $this->id,
'quantity' => $this->quantity,
];
}
}
class Bascket
{
private $products = array();
/* for testing */
function __construct()
{
$this->products[] = new Product(26, 1006);
}
function add(int $id, int $quantity)
{
...
}
function delete(int $id, int $quantity)
{
...
}
public function toJson(){
$products = [];
foreach ($this->products as $product) {
$products[] = $product->toArray();
}
return json_encode(
[
'products' => $products
],
JSON_PRETTY_PRINT
);
}
function __get($field) {
return $this->$field;
}
}
And that's how I would theoretical create a PHP JSON easier.
But look at take_bascket.php
:
<?php
session_start();
include "classes/bascket.php";
if(!isset($_SESSION["bascket"])) {
$_SESSION["bascket"] = serialize(new Bascket());
}
var_dump(((unserialize($_SESSION["bascket"]))->toJson()));
/*
* output:
* string(98) "{ "products": [ { "id": 26, "quantity": 1006 } ] }"
*/
display_bascket()
: function display_bascket() {
$.ajax({
url: 'php/take_bascket.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(bascket){
//bascket = JSON.parse(bascket);
$("#content").html(bascket);
}
});
}
If I don't use JSON.parse()
, it'll display the next plain text:
string(98) "{ "products": [ { "id": 26, "quantity": 1006 } ] }"
Instead, if I use JSON.parse(), I have a console error:
Uncaught SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse (<anonymous>)at Object.success (display_bascket.js:10)
at j (jquery.js:2) at Object.fireWith [as resolveWith] (jquery.js:2)
at x (jquery.js:4) at XMLHttpRequest.b (jquery.js:4)
I suggest that in each object you create a method that will return a JSON representation of that object.
For instance (filename: products.php):
class Product {
private $name;
private $value;
private $quantity;
public function __construct($name, $value, $quantity){
$this->name = $name;
$this->value = $value;
$this->quantity = $quantity;
}
public function toArray(){
return [
'name' => $this->name,
'value' => $this->value,
'quantity' => $this->quantity,
];
}
}
class Basket{
private $products = [];
public function addProduct(Product $p){
$this->products[] = $p;
}
public function toJson(){
$products = [];
foreach ($this->products as $p) {
$products[] = $p->toArray();
}
return json_encode(
[
'products' => $products
],
JSON_PRETTY_PRINT
);
}
}
$b = new Basket();
$b->addProduct(new Product('Apple', 1, 5));
$b->addProduct(new Product('Banana', .5, 2));
$b->addProduct(new Product('Carrots', .35, 6));
echo $b->toJson();
This will generate a JSON object that you can use with jQuery .getJSON()
method.
Like the example below (filename: products.html):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"> </script>
</head>
<body>
<h3>Product list</h3>
</body>
<script>
$(function(){
$.getJSON( "products.php", function( data ) {
console.log(data);
var items = [];
$.each( data.products, function( key, val ) {
items.push( "<li>Name: " + val.name + " | Quantity: " + val.quantity + " | Price: " + val.value + "</li>" );
});
$( "<ul/>", {
html: items.join( "" )
}).appendTo( "body" );
});
});
</script>
</html>
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.