I've only ever used ajax to write to sessions or perform inserts but now i'm needing to get a response. I have managed to go through several examples and 'kind of' got it working but i've reached a point where i'm stuck. I'm looking for a dumbed down working model that i can then use as a base to expand my knowledge on.
AIM
To read the session details (cart info) and update them in the sidebar without the page refreshing
Jquery
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "buy-page-handler.php",
data: $(this).serialize(),
success: function(result){
jq_json_obj = $.parseJSON(result); //Convert the JSON object to jQuery-compatible
if(typeof jq_json_obj == 'object'){ //Test if variable is a [JSON] object
jq_obj = eval (jq_json_obj);
//Convert back to an array
jq_array = [];
for(elem in jq_obj){
jq_array.push(jq_obj[elem]);
}
console.log(jq_array); // I THOUGHT I COULD LOOP THROUGH Jq_array BUT CANT GET IT DISPLAYING ANYTHING
}else{
console.log("Error occurred!");
}
}
});
PHP
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include ("cart_functions.php");
if(isset($_POST["id"]))
{
$pid = $_POST['id'];
$q = $_POST['qty'];
$name = $_POST['name'];
$desc = $_POST['desc'];
$price = $_POST['price'];
$productimg = $_POST['img'];
addtocart($pid,$q,$name,$desc,$price,$productimg);
echo json_encode($_SESSION['cart']);
}
?>
CONSOLE LOG
[{"productid":"1","qty":"1","productname":"item 1","productdesc":"this thing","productprice":"20.00","productimg":""},{"productid":"2","qty":"1","productname":"item 2","productdesc":"this other thing","productprice":"10.00","productimg":""}]
It appears that it is working, however i can't seem to attach a variable name to the returned array and work with it to display it in the #sidebar. Any assistance would be greatly appreciated.