php - Working with a JSON array -
php - Working with a JSON array -
i've ever used ajax write sessions or perform inserts i'm needing response. have managed go through several examples , 'kind of' got working i've reached point i'm stuck. i'm looking dumbed downwards working model can utilize base of operations expand knowledge on.
aim
to read session details (cart info) , update them in sidebar without 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 json object jquery-compatible if(typeof jq_json_obj == 'object'){ //test if variable [json] object jq_obj = eval (jq_json_obj); //convert array jq_array = []; for(elem in jq_obj){ jq_array.push(jq_obj[elem]); } console.log(jq_array); // thought loop through jq_array cant displaying }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 working, can't seem attach variable name returned array , work display in #sidebar. assistance appreciated.
your script seems overly complicated. looks can access variables jq_json_obj[0].productid
, don't need eval
, loop.
if set datatype
, don't need parse result either , can cut down to:
$.ajax({ type: "post", url: "buy-page-handler.php", data: $(this).serialize(), datatype: "json", // set datatype returned info success: function(result) { // homecoming string has been parsed // seem have object stored in array i'll utilize // variable clarity var product = result[0]; console.log(product.productname); // should give "item 1" // etc. } });
note: if not work, should console.log(result);
see have exactly. hard see processing have done.
php jquery ajax json
Comments
Post a Comment