Search code examples
jqueryajaxcodeignitercart

Jquery & CI UNDEFINED data - response from $.ajax


What i’m trying to do : i’m trying to do a shopping cart that doesn’t reload the page each time you click on an item, but saves the selected items in the session.

so after the user clicks “add”, i’ll add the value to my session, then i’ll parse the session values in a json array and i’ll append the whole “product list” inside the cart..

The problem is that for some reason, it’s printing “Undefined” for data.dados[0].id_prod, while it should be printing the id of the product..

So, this is my controller:

//get the ajax ‘get’ ...
if (isset($_GET[‘id_prod’]) && !empty($_GET[‘id_prod’]) && isset($_GET[‘qnt’]) && !empty($_GET[‘qnt’])) {

  $ma = $this->loja_model->add_carrinho($_GET[‘id_prod’], $_GET[‘qnt’]);
  $carr = $this->loja_model->list_carrinho();

  if ( isset($carr) && !empty($carr) ) {
    $array[‘data’][‘dados’]=$carr[0];
    $array[‘data’][‘valor’]=$carr[1];
echo json_encode($array);
  }

  }

and it prints this json object after $.ajax was called:

{“data”:
  {“dados”:

  [
    {“id_prod”:“1”,“id_cat”:“4”,“produto”:“Barco Velho”,“descricao”:“Barco de madeira tipo canoa.”,“valor”:“100.00”,“custo”:“0”,“qnt”:49},
    {“id_prod”:“2”,“id_cat”:“1”,“produto”:“Fusca 68”,“descricao”:“Raridade. Impec?vel. Roda. Trio. Som. Estepe original.”,“valor”:“4000.00”,“custo”:“0”,“qnt”:11},
    {“id_prod”:“3”,“id_cat”:“2”,“produto”:“MonoMoto”,“descricao”:“Moto de uma roda s?”,“valor”:“18000.00”,“custo”:“0”,“qnt”:2}
  ],

  “valor”:84900}
}

This is my JS file :

       $.ajax({
  url:      ‘http://mdk-store.com/loja/index.php/lojavirtual/index’,
  data: data_prod,
  type:    ‘GET’,
  dataType:  ‘json’,
  async: true,
  success: function(data) {
    window.alert(data[0].id_prod);
  }


  });

Solution

  • According to the JSON you should be using: data.data.dados[0].id_prod.

    In order to access the data in the way you expect your JSON would need to look like this:

    [
      {“id_prod”:“1”,“id_cat”:“4”,“produto”:“Barco Velho”,“descricao”:“Barco de madeira tipo canoa.”,“valor”:“100.00”,“custo”:“0”,“qnt”:49},
      {“id_prod”:“2”,“id_cat”:“1”,“produto”:“Fusca 68”,“descricao”:“Raridade. Impec?vel. Roda. Trio. Som. Estepe original.”,“valor”:“4000.00”,“custo”:“0”,“qnt”:11},
      {“id_prod”:“3”,“id_cat”:“2”,“produto”:“MonoMoto”,“descricao”:“Moto de uma roda s?”,“valor”:“18000.00”,“custo”:“0”,“qnt”:2}
    ]