Solved

I am trying to update a value when data = success but is its giving an error Jquery/PHP

Posted on 2016-10-14
28
51 Views
Last Modified: 2016-11-22
I am trying to update a session called $_SESSION['counting']
But its not working, i made this based on what i learned from a user here.
look my code.
index.php i have this....
<li><a href="checkout.php">
<i class="fa fa-cart-plus cart_size" aria-hidden="true"></i>
</span>&nbsp;Carrinho<span class="badge  total_items"><?php echo $_SESSION['counting'];?></span>
</a></li>

Open in new window


i am trying to update   $_SESSION['counting'] inside of my span tag.

and this is my script in index.php
  $('.actions').click(function(e){ 
  e.preventDefault();
  var action = $(this).attr('data-action'); //identifica a ação do botão
  var id = $(this).attr('product_id');
 
  
  console.log("triggered action " + action + " for product " + id); //debugging
  $.ajax({
  url: 'cart_functions.php',
  type : 'GET',
  data: {action:action,prod_id:id},
  dataType: 'json'
  // Be consistent and use .done()
}).done(function(data) {

  if (data.result == "success") {
     console.log(data);
   // $(".product" + id).text(data.val);
    //$('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
    $('.total_items').html(data.items); <--- this is the problem

  }
  else {
    alert("error");
  }
}).fail(function(jqXHR, textStatus, errorThrown) { //in case of server/network error
  console.log("An error occurred whilst attempting to contact the server: " + jqXHR.status + " " + textStatus + " " + errorThrown);
});
});

Open in new window


and this is my cart_functions.php

//some code here
$product_count = count(array_filter(array_keys($_SESSION), function($x) {
return substr($x, 0, 8) == 'product_'; }));
$_SESSION['counting']=$product_count;

 // Calculate subtotal here

$result['totals'] = new stdClass;
$value = $_SESSION[$prodname];
$result['subtotal'] =  number_format($value * $_SESSION['icms'.$prod], 2, '.', ''); /* subtotal result here */
$result['cost'] = $_SESSION['icms'.$prod] ;/* Product cost here */  

$result['items']=$_SESSION['counting'];

echo json_encode($result);
//some code here

Open in new window


as you can see my $result['items']=$_SESSION['counting'];
$result['items'] is defined.
but i get an error in my console saying : Uncaught ReferenceError: data is not defined(…)
When i paste this $('.total_items').html(data.items); in console.
Why is that happening?
0
Comment
Question by:James Allan
  • 13
  • 10
  • 5
28 Comments
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
I am trying to update a session called $_SESSION['counting']
In your HTML you are simply echoing the value that is stored in $_SESSION['counting']. You are not updating it.

You have at least two invalid element attributes -- aria-hidden and product_id. Are you using a custom doctype DTD?

The following line is confusing because action is a variable, but it is being used as an object key. I have a feeling that jQuery doesn't have problem with this but I would consider it a bad practice. (Line 11 from your script in index.php)
data: {action:action,prod_id:id},

Open in new window

I do not see a result key/value pair in the $result array that is JSON encoded and returned by cart_functions.php. So unless you have omitted that part, the following should generate an error because data.result would not exist.
if (data.result == "success") {

Open in new window

Please post what is being displayed in the console. I have a feeling that cart_functions.php is not returning what you think it is. The error suggests that the returned data does not exist.

Is this page live so that we can see the ajax conversation?
0
 
LVL 9

Expert Comment

by:Brian Tao
Comment Utility
Uncaught ReferenceError: data is not defined(…)
This only happens when you paste this $('.total_items').html(data.items); in console, but no error when your ajax call returns, right?

To answer your question
Why is that happening?
:
Because you're out of scope.  data is only available in the done(function(data){}) event handler but you're trying to refer to it in the console which is at a global (window) level.

If the "total_items" span doesn't get updated, then we'll have to see the whole picture.
0
 

Author Comment

by:James Allan
Comment Utility
i will explane all...

1. this script i reused from my checkout page,where i have 3 buttons where the function for it, is in cart_functions.php.
 this is the full code for it.
<?php header('Content-Type: application/json');
session_start();

if (isset($_GET['action'])) {
  $action = $_GET['action'];
  $prod   = $_GET['prod_id'];
  $prodname = 'product_'.$prod;

$result;
 switch ($action) {
    case 'add':
        $result = add_prod($prod, $prodname);
    break;
    case 'plus':
        $result = plus_prod($prod, $prodname);
         
    break;
    case 'remove':
        $result = remove_prod($prod, $prodname);
    break;
    case 'delete':
        $result = delete_prod($prod, $prodname);
    break;
    default:
        $result = ['result'=>'error'];
    break;
  }
 
}

$product_count = count(array_filter(array_keys($_SESSION), function($x) {
return substr($x, 0, 8) == 'product_'; }));
$_SESSION['counting']=$product_count;

 // Calculate subtotal here
$result['totals'] = new stdClass;
$value = $_SESSION[$prodname];
$result['subtotal'] =  number_format($value * $_SESSION['icms'.$prod], 2, '.', ''); /* subtotal result here */
$result['cost'] = $_SESSION['icms'.$prod] ;/* Product cost here */  
$result['items']=$_SESSION['counting'];

echo json_encode($result);

function add_prod($prod, $prodname){
//add function
$_SESSION[$prodname] = 1;
$_SESSION[$prodname.'icms'];
 return ['result'=>'success'];
}
//add +1 function
function plus_prod($prod, $prodname){
  $_SESSION[$prodname]++;
  return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}

//minus -1 function
function remove_prod($prod, $prodname){
  //sua função para remove
  $_SESSION[$prodname]--;
  return ['result'=>'success', 'val'=>$_SESSION[$prodname]];
}

//delete function
function delete_prod($prod, $prodname){
  //sua função para delete
unset($_SESSION[$prodname]);
unset($_SESSION['icms'.$prod]); 
  return ['result'=>'success'];
}

Open in new window


2. And in my checkout.php i have this script that works with and include from cart.php.

My cart.php i have one function,that is displaying all products in session.
so in my checkout i have <?php cart(); ?> that this function comes from cart.php


(this script is responsable for my drop downs to send data and get result of costs of product)
calculates.php code here

so my jquery script on checkout is..
 $(document).ready(function() {

  $('.fabric, .size').on('change', sendData);

  function sendData() {
   //use the data-id attribute of the selected element to match the correct elements
   var id = $(this).data("id");
    var action = $(this).attr('data-action');
    var fabricID = $('.fabric[data-id=' + id +']').val(); 
    var sizeID   = $('.size[data-id=' + id +']').val();

    if ( fabricID !== "" && sizeID !== "") {
      $.ajax({
            type     : 'GET',
            url      : 'calculates.php',
            dataType : 'json',
            data     : {
                prod_id:id,
                fabric_id: fabricID,
                action:action,
                size_id: sizeID
            }
        }).done(function(data) {
          console.log(data);
          $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
          $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
           
            
           
        });
      }
  }
});

Open in new window


and the second script in checkout is responsable for my buttons add, remove and delete.
$('.actions').click(function(e){ 
  e.preventDefault();
  var action = $(this).attr('data-action'); //identifica a ação do botão
  var id = $(this).attr('product_id');
  var cost_id = $(this).data("id");
  
  console.log("triggered action " + action + " for product " + id); //debugging
  $.ajax({
  url: 'cart_functions.php',
  type : 'GET',
  data: {action:action,prod_id:id},
  dataType: 'json'
  // Be consistent and use .done()
}).done(function(data) {
  if (data.result == "success") {
    $(".product" + id).text(data.val);
    $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
  }
  else {
    alert("error");
  }
}).fail(function(jqXHR, textStatus, errorThrown) { //in case of server/network error
  console.log("An error occurred whilst attempting to contact the server: " + jqXHR.status + " " + textStatus + " " + errorThrown);
});
});

Open in new window


3.So i am trying to use some of these things in my index.php.
In index i have my products gallery.
my gallery_function.php
i have these button
$add_btn='<a type="button" class="btn btn-primary btn-sm pull-right btn_add actions add" data-action="add" product_id="'.$id.'"><i class="fa fa-cart-plus" aria-hidden="true"></i></span>&nbsp;Adicionar</a>';

Open in new window

this function is included in my index.php
this is the button that sends a product to checkout.

So i am trying to do, is when these button above sends a product to checkout, it will be counted in my span tag in the beginning of the question i made.

Sorry for this big information, but now you will understand what im doing
0
 

Author Comment

by:James Allan
Comment Utility
All this is working, less my script in index.php.
Where i am trying to update the value in my span tag
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
OK. I misunderstood the question. I think Brian Tao has answered why you're getting the error. But I also think your ultimate issue is the fact that $_SESSION['counting'] is not being updated on your page. Correct?

Your actions buttons are using AJAX to send an item to the back end which is changing the value of $_SESSION['counting']. Correct? But the value displayed in your <span> tag is not changing. Correct?

When the page loads, the current value of $_SESSION['counting'] is echoed in the page source code. There is no link after that point between the $_SESSION['counting'] variable on the back end and the value displayed in the <span> tag. Nor is there a link from the page being displayed in the browser to the $_SESSION['counting'] variable on the back end. When the page is loaded or refreshed, the back end $_SESSION array is uploaded to the front end and stored in a cookie. It is not dynamic.

Your ajax .done() clause would have to update the text in the span. It could do this from the data.items value returned from the ajax call. (See line 18 below)
$('.actions').click(function(e){ 
  e.preventDefault();
  var action = $(this).attr('data-action'); //identifica a ação do botão
  var id = $(this).attr('product_id');
  var cost_id = $(this).data("id");
  
  console.log("triggered action " + action + " for product " + id); //debugging
  $.ajax({
  url: 'cart_functions.php',
  type : 'GET',
  data: {action:action,prod_id:id},
  dataType: 'json'
  // Be consistent and use .done()
}).done(function(data) {
  if (data.result == "success") {
    $(".product" + id).text(data.val);
    $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
    $(".total_items").text(data.items);
  }
  else {
    alert("error");
  }
}).fail(function(jqXHR, textStatus, errorThrown) { //in case of server/network error
  console.log("An error occurred whilst attempting to contact the server: " + jqXHR.status + " " + textStatus + " " + errorThrown);
});
});

Open in new window

0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
This still does not address the invalid element attributes unless you are using a custom doctype DTD.
0
 

Author Comment

by:James Allan
Comment Utility
Yes you are correct Kim!

Like sense my add to cart button is sending data by ajax to cart_functions.php, and i created the $result['items'].
I tought that when i click on add to cart, my script in index should grab the counted session product,and send the data to $result['items'];
where on success should by updated in my span tag.
Do you have a tip to how can i make this better so it works?
0
 

Author Comment

by:James Allan
Comment Utility
i did not declare DTD.

i just started my index.php with html/head/body tags
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Did you see where I added line 18 in the code above? That should update the span text.

Are you sure your add button is working? Are there multiple product items in the $_SESSION super global variable?
0
 

Author Comment

by:James Allan
Comment Utility
I used the code as in line 18 and still didn't work.
only works on refresh page.
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Do you have multiple elements with the class "total_items"? It may only be changing the first one. Can you post a link to the live page? Otherwise, can you give the span a unique id that we can target?
1
 
LVL 9

Expert Comment

by:Brian Tao
Comment Utility
Can you try changing the following line in cart_functions.php:
$result['items']=$_SESSION['counting'];

Open in new window

to
$result['items']=999;

Open in new window

just for debugging, and let's see if your span tag gets updated to 999?  I started wondering it's not that the tag doesn't get updated.................
1
 

Author Comment

by:James Allan
Comment Utility
Brian it got updated to 999.
It looks like that only my session doesn't update when i add product to cart.
only on refresh.
0
 

Author Comment

by:James Allan
Comment Utility
Kim no i dont have multiple elements with the same class.
i gave a id for in my span


<li><a href="checkout.php"><i class="fa fa-cart-plus cart_size " ></i></span>&nbsp;Carrinho <span class="badge" id="items">
<?php 
   if(isset($_SESSION['counting'])){
       echo $_SESSION['counting'] ; 
       }else{
       echo 0; 
       }
 ?>
</span></a></li>

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Then changing line 18 to the following should work.
    $("#items").text(data.items);

Open in new window

If this doesn't change the text content of the "items" span, we need to be able to see the live code to see what's preventing it.
0
 
LVL 9

Assisted Solution

by:Brian Tao
Brian Tao earned 500 total points
Comment Utility
Questions:
  1. what is this line $_SESSION[$prodname.'icms']; doing in your function add_prod($prod, $prodname)? I don't see such key being used in anywhere else.
  2. what is line #9 $result; doing?
  3. what is line #36 $result['totals'] = new stdClass; doing?
  4. what is this line unset($_SESSION['icms'.$prod]); doing in your function delete_prod($prod, $prodname)? I don't see it being set in anywhere in your script.

And 1 more thing to try:
change the following line
$result['items']=$_SESSION['counting'];

Open in new window

to
$result['items']=$product_count;

Open in new window

and see if it works.
0
 

Author Comment

by:James Allan
Comment Utility
I'm back after solving some problems, but still, i am having problem with my cart product counter .

Now what i did was, i used a function to count products.
////code from cart_functions.php////
$total_in_cart=count($_SESSION['product']);  

Open in new window

$_SESSION['products']=$total_in_cart;

Open in new window

$result['items'] = $_SESSION['products']; 

Open in new window



this code is from my index, where i have cart icon
<li><a href="checkout.php" ><i class="fa fa-cart-plus cart_size " ></i></> Carrinho <span class="badge items" id="items"  >
 <?php echo $_SESSION['products']; ?>
</span></a></li>

Open in new window


The script in index.
$('.actions').click(function(e){ 
  e.preventDefault();
  var action = $(this).attr('data-action'); //identifica a ação do botão
  var id = $(this).attr('product_id');

  
  console.log("triggered action " + action + " for product " + id); //debugging
  $.ajax({
  url: 'cart_functions.php',
  type : 'GET',
  data: {action:action,prod_id:id},
  dataType: 'json'
  // Be consistent and use .done()
}).done(function(data) {
    console.log("ajax call returned the following: " + JSON.stringify(data));
  if (data.result == "success") {
   // $(".product" + id).text(data.val);
   // $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
    $("#items").html(data.items);
    
   
  }
  else {
    alert("error");
  }
}).fail(function(jqXHR, textStatus, errorThrown) { //in case of server/network error
  console.log("An error occurred whilst attempting to contact the server: " + jqXHR.status + " " + textStatus + " " + errorThrown);
});
});

Open in new window


I did all what you guys said here, but no solution.
0
 
LVL 9

Expert Comment

by:Brian Tao
Comment Utility
You haven't tried the one in my comment 41847993
0
 

Author Comment

by:James Allan
Comment Utility
I did but still nothing
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Do you know that $_SESSION['product'] contains an array of products?

Can you post a link to the live page? We need to see what's being returned by the ajax query.
0
 
LVL 9

Expert Comment

by:Brian Tao
Comment Utility
Ok, when you changed it to 999 it changes the screen display, but nothing else worked, right?
Apparently it means neither of your $_SESSION['counting'] or the new $_SESSION['products'] is working in the cart_functions.php.
Can you please attach your files here and not just copy&paste part of your code?  Sometimes it's the hidden part that's causing the problem.

And, you haven't answer my questions in the same comment 41847993
0
 

Author Comment

by:James Allan
Comment Utility
My cart_functions.php
the cart_functions is responsible for making my buttons add, plus, minus and remove to work.
And when these buttons are clicked my cost,and sub-total changes.
This is all working fine =D

My cart.php
In cart.php i have only a function that gives me data and dropdown options for each product.

My calculates.php
calculates.php is responsible for giving the cost based on fabric and size options from the dropdowns.

My checkout.php
Is where everything works with script above.

My index.php
In here is my product gallery, and my product counter
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Please help us help you by answer the questions that have been asked.
Do you know that $_SESSION['product'] contains an array of products?

Can you post a link to the live page? We need to see what's being returned by the ajax query.
0
 

Author Comment

by:James Allan
Comment Utility
Try this
http://192.168.0.100/system/clientes/gallery/

email: jhon@mail.com
password:123
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
This is a local network IP address. Do you have a public IP address?
0
 

Accepted Solution

by:
James Allan earned 0 total points
Comment Utility
Hello guys!

Good news, i fix this problem.
What i did was,i created a new file cart_function2.php
And i took off all the code,i let only my add code.
And it worked fine.

this is how my code looks like now:
<?php header('Content-Type: application/json');

session_start();





if (isset($_GET['action'])) {
  
  $action = $_GET['action'];
  $prod   = $_GET['prod_id'];
  
 // $prodname = $_SESSION['product'][$prod];

  

$result="";

  switch ($action) {
    
    case 'add':
        $result = add_prod($prod);
    break;
   
    default:
        $result = ['result'=>'error'];
    break;
  }



}



// Calculate subtotal here
$result['totals'] = new stdClass;
$total_in_cart=count($_SESSION['product']);  
$_SESSION['products']=$total_in_cart;


$result['items'] =  $total_in_cart; 

 echo json_encode($result);





function add_prod($prod){
  //add function
$_SESSION['product'][$prod] = 1;
$_SESSION['products']++;
return ['result'=>'success'];
}



?>

Open in new window

0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
I'm glad you figured it out.
0
 

Author Closing Comment

by:James Allan
Comment Utility
I rewrite my code , there was some stuffs that was not working in the same script.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

SASS allows you to treat your CSS code in a more OOP way. Let's have a look on how you can structure your code in order for it to be easily maintained and reused.
This article discusses four methods for overlaying images in a container on a web page
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now