Solved

jquery is not updating my php value when user selects dropdown option

Posted on 2016-10-13
44
59 Views
Last Modified: 2016-10-13
I got two dropdowns in each product in my cart. When i select my both option my class on success is not updating the cost. It only updates when i refresh the page,it does not give me my cost on change, i dont want to refresh my page to get the cost.
this is my script...

$(document).ready(function() {

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

  function sendData() {

  var id = $(this).data("id");
  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,
                size_id: sizeID
            }
        }).done(function(data) {
            $('.cost' + id).text(data.val);
            $('.subtotal' + id).load(data.val);
         });
      }
  }
});

Open in new window


this is where i am trying to update when user select his product options

<td class="product'.$id.'">'.$value.'</td>
<td class="cost" data-id="'.$id.'">R$: '.$_SESSION['icms'.$id].'</td>
<td class="subtotal"  data-id="'.$id.'">R$: '.$value * $_SESSION['icms'.$id] .'</td>

Open in new window


My $value  holds the quantity of my product. And other problem that i'm getting is when i click in my plus and remove button,i don't get my subtotal to updated either.

And this script handles my  $value to keep updating when i click on my button.

$('.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',
    success: function(data)
    {
      console.log("ajax call returned the following: " + JSON.stringify(data)); //debugging
      if (data.result == "success") {
        if (action == "plus" || action == "remove")
        {
          console.log("identified product td for " + id + ": " + $(".product" + id).length); //debugging
          $(".product" + id).text(data.val);
          $(".subtotal" + cost_id).text(data.val);
          //update the UI with the new total
        }

Open in new window


So as you can see i used in both scripts my class subtotal. So it can update when i click in my plus or remove button and on dropdown selection changes the subtotal and the cost for each product. Why my jquery is not updating my cost and subtotal?
Please some help i am a noob at jquery.
0
Comment
Question by:James Allan
  • 27
  • 17
44 Comments
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841818
What is this code meant to be doing?
        }).done(function(data) {
            $('.cost' + id).text(data.val);
            $('.subtotal' + id).load(data.val);
         });

Open in new window

You are concatenating id to the .cost class and then trying to select an element with that class.
If we look at your markup you have
<td class="cost" data-id="'.$id.'">R$: '.$_SESSION['icms'.$id].'</td>

Open in new window

But the resulting selector will be something like .cost123 which won't match anything.

Are you trying to target the .cost <td> with data-id = to the id returned ? if so then you should be doing something like this
$('.cost[data-id=' + id + ']').html('R$:' + data.val);

Open in new window


Again this line confuses me
$('.subtotal' + id).load(data.val);

Open in new window

For the same reason regarding the selector BUT also because of your use of load - load is for doing an AJAX load of an external resource into the matched elements.
You want to be doing something similar to cost
$('.subtotal[data-id=' + id + ']').html('R$:' + data.val);

Open in new window


The same would apply to these lines
          $(".product" + id).text(data.val);
          $(".subtotal" + cost_id).text(data.val);

Open in new window

0
 

Author Comment

by:James Allan
ID: 41841866
The  $(".product" + id).text(data.val); in my second script updates my $value perfectly on click of my buttons add and remove.
But it was not updating my subtotal.
i used in my first script
$('.subtotal[data-id=' + id + ']').html('R$:' + data.val);
$('.cost[data-id=' + id + ']').html('R$:' + data.val);

Open in new window

And now all my values is displaying R$:undefined
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841892
I am seeing a problematic design here - the product will work as per your original coding because you are creating the <td> with a class of .product + id (<td class="product123">)

A better design pattern would be this
'<td class="product" id="product_"' . $id . '">'

Which would allow you to address the product in the same way
$('product_' + id)

Open in new window

Effectively the same but a better coding practice.

Regarding the undefined - that would be because the data returned in your AJAX call is not what you are expecting.
Can you do this in the done() of your first script
.done(function(data) {
console.log(data);
            $('.cost' + id).text(data.val);
            $('.subtotal' + id).load(data.val);
         });

Open in new window

Inspect the console and see what the return from the GET is. Post that here.
1
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841895
Also, take some time to familiarise yourself with HEREDOC - it will make a big difference in structuring your output. Instead of

echo '<td class="product" id="product_' . $id . '">';

Open in new window

you would have
echo <<< CELL
      <td class="product" id="product_{$id}">
CELL;

Open in new window

HEREDOC allows you to mix double and single quotes as well as embed variables.
1
 

Author Comment

by:James Allan
ID: 41841915
this is my full cart function look how it was build.

foreach ($_SESSION as $name => $value) {
        if($value > 0){
            if(substr($name, 0, 8 ) == "product_"){
                $length = strlen($name) -8;
                $item_id = substr($name,8 , $length);

                $query = "SELECT * 
                          FROM gallery2 
                          WHERE gallery2.id =".escape_string($item_id). "";
                $run_item = mysqli_query($conn,$query);

                
                while($rows = mysqli_fetch_assoc($run_item)){ 
               $vari   = $rows['variante'];
               $num    = $rows['title'];
               $id     = $rows['id'];

        
               if(!isset($_SESSION['icms'.$id])) {
               $_SESSION['icms'.$id]='0';
               }else{
              $_SESSION['icms'.$id];
               }

         $btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';
         $btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';
         $btn_delete ='<button type="button" class="btn btn-default actions" data-action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></button>';

        if($rows['variante'] < 1){
            $vari="";
        }else{
            $vari = "-".$rows['variante'];
        }
        
        $product = '
        <tr>
          <td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
          <td>'.$num.''.$vari.'</td>
          <td style="width:15%;">
              <select name="fabric" class="fabric select form-control selectpicker" required="" data-id="'.$id.'">
                '. $fabric_options . '  
              </select>
          </td>
            
          <td>
            	<select  data-id="'.$id.'" class="select size form-control selectpicker" required style="width:80%;" >
                 <option value="'.$t50.'">50x'.$t50.'</option>
                <option value="'.$t45.'">45x'.$t45.'</option>
                </select>
          </td>
          <td class="product'.$id.'">'.$value.'</td>
          <td class="cost" data-id="'.$id.'">'.$_SESSION['icms'.$id].'</td>
          <td class="subtotal" data-id="'.$id.'">'.$value * $_SESSION['icms'.$id] .'</td>
          <td> 
             '.$btn_add.' '.$btn_remove.' '.$btn_delete.'
          </td>
        </tr>';
        echo $product;  

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841948
This is an example of the changes I would make to the page
NB: This is an example - you will need to read and understand it and then apply it to your code - it may not work in your current code base if you just copy it as I have changed some things.
1. you have an attribute product_id in your <button>'s - this is not a valid attribute. Custom attribute should be prefixed with data-
2. I have used Ternary expressions in place of your if / else for setting values
3. I have used HEREDOC for the strings.
4. Take a look at the docs for substr. You only need to specify a length if you are taking less than the rest of the string. Specifying a start position of 8 is enough to get the last LEN-8 bytes.
5. When embedding variables in strings I have used the { } to enclose the variables.
<?php
foreach ($_SESSION as $name => $value) {
  if($value > 0){
    if(substr($name, 0, 8 ) == "product_"){
      // *** Length is not needed if you are taking the rest of the string
      //$length = strlen($name) -8;
      $item_id   = substr($name,8);

      // *** Create escaped item_id for use in query string
      $escitemid = escape_string($item_id);

      // *** Using HEREDOC for Query
      $query = <<< QUERY
SELECT 
  * 
FROM 
  gallery2 
WHERE 
  gallery2.id ={$escitemid}
QUERY;
    $run_item = mysqli_query($conn,$query);
    while($rows = mysqli_fetch_assoc($run_item)){ 
      $vari   = $rows['variante'];
      $num    = $rows['title'];
      $id     = $rows['id'];
      
      // *** Create index for SESSION
      $icmsid = "icms{$id}";
      
      // *** Subsituted Ternary expression for if / else
      $_SESSION[$icmsid] = isset($_SESSION[$icmsid]) ? $_SESSION[$icmsid] : 0;

      // *** NB: custom data attributes should be prefixed with "data"
      $btn_add = <<< BUTTON
      <button type="button" class="btn btn-success actions plus" data-action="plus" data-product_id="{$id}">
        <i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i>
      </button>

BUTTON;
      // *** NB: custom data attributes should be prefixed with "data"
      $btn_remove = <<< BUTTON
      <button type="button" class="btn btn-warning actions less" data-action="remove" data-product_id="{$id}">
        <i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i>
      </button>

BUTTON;
  
      $btn_delete = <<< BUTTON
      <button type="button" class="btn btn-default actions" data-action="delete" data-product_id="{$id}" onclick="deleteRow(this)">
        <i class="fa fa-times fa-lg" aria-hidden="true"></i>
      </button>
BUTTON;

    // Substitute Ternary expression for if / else and use { } encapsulation of variable in string
    $vari = ($rows['variante'] < 1) ? '' : "-{$rows['variante']}";

    // Pre calculate values to be used in output
    $subtotal = $value * $_SESSION[$icmsid];

    $product = <<< TABLE
        <tr>
          <td style="width:100px;">
            <img src="../{$rows['image']}" style="width:90%;border: 1px solid black;">
          </td>
          <td>{$num}{$vari}</td>
          <td style="width:15%;">
              <select name="fabric" class="fabric select form-control selectpicker" required="" data-id="{$id}">
                {$fabric_options}
              </select>
          </td>
          <td>
              <select data-id="{$id}" class="select size form-control selectpicker" required style="width:80%;" >
          <option value="{$t50}">50x{$t50}</option>
          <option value="{$t45}">45x{$t45}</option>
              </select>
          </td>
          <td class="product" id="product{$id}">{$value}</td>
          <td class="cost" data-id="{$id}">{$_SESSION[$icmsid]}</td>
          <td class="subtotal" data-id="{$id}">{$subtotal}</td>
          <td> 
            {$btn_add} {$btn_remove} {$btn_delete}
          </td>
        </tr>
TABLE;
        echo $product;  

Open in new window


You still need to post the results of the console.log(data) I asked for in my earlier post.
1
 

Author Comment

by:James Allan
ID: 41841957
What i get with console.log(data); is the value of my cost
exemple:
first dropdown i selected a fabric named Velvet and  the the size dropdown i selected size 50
so i get the cost for that product is 42.25. in console.
0
 

Author Comment

by:James Allan
ID: 41841966
Julian in my console shows only the cost based on my dropdown selection.
When used console.log
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841974
Can you post the console output.

In your code you have this
       }).done(function(data) {
            $('.cost' + id).text(data.val);
            $('.subtotal' + id).load(data.val);
         });

Open in new window


This implies a JSON return where the returned object has a property val that is the value you want to use. However you are getting undefined - so we need to see what is actually coming back.

Please copy and paste (or screenshot) the contents of the GET response.
0
 

Author Comment

by:James Allan
ID: 41841985
well 'im sorry, i didnt said that i used the fixed code that you provided.

$('.cost[data-id=' + id + ']').html('R$:' + data.val);
$('.subtotal[data-id=' + id + ']').html('R$:' + data.val);

Open in new window


this one in giving me the R$:undefined.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41841989
I still need to see the return from the GET - we are going to get nowhere unless you post that.
0
 

Author Comment

by:James Allan
ID: 41842016
getting.png
i get this using

  }).done(function(data) {
            $('.cost' + id).text(data.val);
            $('.subtotal' + id).load(data.val);
         });

Open in new window


and this
getting2.png
when i use

.done(function(data) {
          console.log(data);
           $('.cost[data-id=' + id + ']').html('R$:' + data.val);
           $('.subtotal[data-id=' + id + ']').html('R$:' + data.val);
        });

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842109
So that is telling me there is no JSON response which means you should not have a dataType: "json" in your AJAX paramters and your code should change to

.done(function(data) {
           $('.cost[data-id=' + id + ']').html('R$:' + data);
           $('.subtotal[data-id=' + id + ']').html('R$:' + data);
        });

Open in new window


But something is still not making sense - in your PHP code your subtotal is worked out like this
<td class="subtotal"  data-id="'.$id.'">R$: '.$value * $_SESSION['icms'.$id] .'</td>

Open in new window

$value * $_SESSION

But you are not doing the same in your JavaScript code - you just trying to display the value? You are assuming that product cost and subtotal are the same i.e. only 1 item in the cart?
0
 

Author Comment

by:James Allan
ID: 41842176
The value is my quantity of the product.
So if i have 3x of a product so value will multiply 3 times with $_SESSION['icms'.$id]
so in the
<td class="subtotal"  data-id="'.$id.'">R$: '.$value * $_SESSION['icms'.$id] .'</td>

Open in new window


i will get the subtotal in the same place where it calculates .$value * $_SESSION['icms'.$id].
if i have 1x of a product in cart i will have the cost of it and the sub total will be the same.
because it one.
0
 

Author Comment

by:James Allan
ID: 41842190
i change my code to this.

$subtotal=$value * $_SESSION['icms'.$id];
$cost=$_SESSION['icms'.$id];

Open in new window


<td class="cost" data-id="'.$id.'" >'.$cost.'</td>
 <td class="subtotal" data-id="'.$id.'">'.$subtotal .'</td>

Open in new window

0
 

Author Comment

by:James Allan
ID: 41842200
look a made a video to explain whats going on.
https://youtu.be/V6H4rqgFr40
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842203
No, you don't understand - the PHP code is fine - I know what you are doing but in your JavaScript code there does not seem to be any provision for doing the same. You use the same return value for both the Product and the SubTotal.

Did you try this
.done(function(data) {
           $('.cost[data-id=' + id + ']').html('R$:' + data);
           $('.subtotal[data-id=' + id + ']').html('R$:' + data);
        });

Open in new window

0
 

Author Comment

by:James Allan
ID: 41842205
Yes i am Julian
0
 

Author Comment

by:James Allan
ID: 41842207
My cost is $_SESSION['icms'.$id]   and the value will multiply:  $value   X  $_SESSION['icms'.$id].
So what you suggest to me fix this?
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842232
This is PHP not JavaScript
  $value   X  $_SESSION['icms'.$id].

Open in new window


You are making an AJAX call back to the server here
$.ajax({
            type     : 'GET',
            url      : 'calculates.php',
            dataType : 'json',
            data     : {
                prod_id:id,
                fabric_id: fabricID,
                size_id: sizeID
            }
        }).done(function(data) {
            $('.cost' + id).text(data.val);         // SAME VALUE
            $('.subtotal' + id).load(data.val); // SAME VALUE
         });
      }

Open in new window

In your success call back you are setting cost and subtotal to the same value. It does not matter what you do in the PHP script nothing will change because the JavaScript is wrong.
Either you need to send back the cost and total in a JSON structure
Example
$return = new stdClass;
$return->cost = $value;
$return->subtotal = $value * $_SESSION['icms'.$id];
die(json_encode($return));

Open in new window

Or you need to manage this in the JavaScript - assuming you are storing icms_$id somewhere on the client.

But before we get there - the original problem was that
It only updates when i refresh the page,it does not give me my cost on change, i dont want to refresh my page to get the cost.
So lets fix that first.
Is this still giving undefined
.done(function(data) {
           $('.cost[data-id=' + id + ']').html('R$:' + data);
           $('.subtotal[data-id=' + id + ']').html('R$:' + data);
        });

Open in new window

Note the change from data.val to data.
0
 

Author Comment

by:James Allan
ID: 41842270
Yeah now it worked  and as you said cost and subtotal are the same value.

Look this generates my costs

calculate.php....
<?php header('Content-Type: application/json');

include_once '../incluedes/conn_cms.php'; //sesion started in here

if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
    $size_id=$_GET["size_id"] ;
    $fabric_id=$_GET["fabric_id"] ;
    $id   = $_GET['prod_id'];
    //$prodname = 'product_'.$prod;


 $query3 =" SELECT * FROM valores_almofadas WHERE size='$size_id' AND price_id ='$fabric_id'";

        $result = mysqli_query($conn,$query3);
        while($rows = mysqli_fetch_assoc($result)){

            if($_SESSION['estado'] == 'SP'){
              $ICMS = $rows['icms_7'];
             }else{
              $ICMS = $rows['icms_12'];
             }
             $_SESSION['icms'.$id]=$ICMS;
             

            

        } echo json_encode( $_SESSION['icms'.$id]);


} 

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842290
echo json_encode( $_SESSION['icms'.$id]);

Open in new window

That is a single value return - only one value is coming back. Where does the $value from your other script come in?

You need to get the $_SESSION['product_...'] value in this script and then return it in the way I described above

$value = $_SESSION['product_ ...']; // Fix to get the right product value
$return = new stdClass;
$return->cost = $value;
$return->subtotal = $value * $_SESSION['icms'.$id];
die(json_encode($return));

Open in new window


And in your JavaScript change to
.done(function(data) {
           $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
           $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
        });

Open in new window

0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:James Allan
ID: 41842333
I fixed like this...
In my calculate.php

if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
    $size_id=$_GET["size_id"] ;
    $fabric_id=$_GET["fabric_id"] ;
    $id   = $_GET['prod_id']; //gets the id of the product

Open in new window


i get the product id :   $id   = $_GET['prod_id'];
and then i made it this way on json return :$value = $_SESSION['product_'.$id];.
so now it looks like this.
     
  $value = $_SESSION['product_'.$id];
        $return = new stdClass;
        $return->cost = $value;
        $return->subtotal = $value * $_SESSION['icms'.$id];
        die(json_encode($return));
and i did what you said to me use in my script.

Open in new window


 $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
$('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);

Open in new window

but now my cost is displaying i.e 1 or 2 or 3

I have a question about the $value.
the $value is defined in my cart function in cart.php.
And i use it in calculates.php like this
$value = $_SESSION['product_'.$id];

Open in new window

So do i have to include my cart.php in calculates.php?
0
 

Author Comment

by:James Allan
ID: 41842359
So fix what was wrong i made like this.

$value = $_SESSION['product_'.$id];
$return = new stdClass;
$return->cost = $_SESSION['icms'.$id];// this was like this   $return->cost =$value;
$return->subtotal = $value * $_SESSION['icms'.$id];
die(json_encode($return));

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842426
I can only guess at how your backend model works - I was leaving it to you to fill in the blanks for the values you needed.
Is it working now?
0
 

Author Comment

by:James Allan
ID: 41842437
Yes now its working!!!
When i did the last thing you said it didnt work because this...

$value = $_SESSION['product_'.$id];
$return = new stdClass;
$return->cost = $_SESSION['icms'.$id];
$return->subtotal = number_format($value * $_SESSION['icms'.$id], 2, '.', '');
die(json_encode($return));

Open in new window

was inside of my while loop in calculate.php, so i tried out of my
if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){

Open in new window

So it worked =D
Now to finalize it i need to make my subtotal update when i click on plus and minus buttons.
0
 

Author Comment

by:James Allan
ID: 41842442
$btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';

$btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';

Open in new window


as you can see in my buttons i have data-action="plus" and data-action="remove".
Now how can i use these data-actions to update my subtotal?
0
 

Author Comment

by:James Allan
ID: 41842448
Look what i did to make my buttons update my subtotal
i created
var action = $(this).attr('data-action');

Open in new window


and on .done(function(data)){.. i put a IF.

done(function(data) {
          console.log(data);
          if(action == 'plus' || action == "remove"){}
           
          $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
          $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
             if(action == 'plus' || action == "remove"){
          $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
           }
        });

Open in new window


but this didnt work.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842495
Your action buttons are increasing and decreasing the items so you have to send this back to your calculate routine so you can update the session.
probably something like this
$.ajax({
           type     : 'GET',
            url      : 'calculates.php',
            dataType : 'json',
            data     : {
                prod_id:id,
                action: action
}).done(function(result) {
   $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
   $('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
});

Open in new window

Then in your calculate.php you check the action parameter and if it exists then decrement the product count if a minus or increment if a plus, recalculate and return as before.

You are going to need to work this out - I don't have all your code, I understand what you want to do and I can guide you but you need to understand what needs to be done and then implement it according to how your code is structured.
1
 

Author Comment

by:James Allan
ID: 41842515
this is my cart_functions.php this handles all my buttons


<?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;
  }
}

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


and this works on my second jquery script
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842535
You are going to need to expand your return to included the updated cost and subtotal values.

Right now you are returning the val only - expand your return array to include the subtotal and product cost.
0
 

Author Comment

by:James Allan
ID: 41842549
Sorry man i don't have a clue what to do now.
Because what handles my buttons is

$('.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',
    success: function(data)
    {
      console.log("ajax call returned the following: " + JSON.stringify(data)); //debugging
      if (data.result == "success") {
        if (action == "plus" || action == "remove")
        {
          console.log("identified product td for " + id + ": " + $(".product" + id).length); //debugging
          $(".product" + id).text(data.val);
         
           
           //update the UI with the new total
        }
        else {
          //here do whatever you need to for the add/delete cases, that wasn't part of the question :-)
        }
      }
      else {
        alert("error");
      }
    },
    error: 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 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 500 total points
ID: 41842570
The first problem is you are trying to maintain your client side model in the browser. This is not a good idea. Your server SESSION holds the current valid values so that is where the data should come from.

What you need to do is this
PHP
 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;
  }
  // Calculate subtotal here
  $result['totals'] = new stdClass;
  $result['subtotal'] = /* subtotal result here */;
  $result['cost'] = /* Product cost here */;
  // Send result back as json
  echo json_encode($result);

Open in new window


jQuery
  $.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") {
    $('.cost[data-id=' + id + ']').html('R$:' + data.cost);
    $('.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

1
 

Author Comment

by:James Allan
ID: 41842614
my buttons ajax functions are in cart_functions.php   and the dropdown data is sent to calculates.php.
So i need then to do what you said in cart_functions.php
and add...
this is what i made.
 
$result['totals'] = new stdClass;
$result['totals']->subtotal = number_format($value * $_SESSION['icms'.$prod], 2, '.', ''); /* subtotal result here */;
$result['totals']->value = $prodname ;/* Product cost here */

Open in new window

.
and it didnt work, and my plus and remove stopped working.

check the urls from both scripts
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41842697
Ok but you need to debug - if the scripts stopped working there probably was an error - check your console and look inside the GET / POST at the response to see if there are any PHP errors there.

I can't write the code for you - I don't have enough information to do that - the principle of what I gave you above is correct - you need to adapt to your code.
0
 

Author Comment

by:James Allan
ID: 41842710
look how is my code now


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;
  }
  // Calculate subtotal here
$result['totals'] = new stdClass;
$result['subtotal']->subtotal = number_format($value * $_SESSION['icms'.$prod], 2, '.', '');  /* subtotal result here */
$result['cost']->value = $prodname ; /* Product cost here */
}


echo json_encode($result);

Open in new window


if i remove:
  // Calculate subtotal here
$result['totals'] = new stdClass;
$result['subtotal']->subtotal = number_format($value * $_SESSION['icms'.$prod], 2, '.', ''); /* subtotal result here */
$result['cost']->value = $prodname ;/* Product cost here */

Open in new window

It works again.

the error i got when i used the code above
 An error occurred whilst attempting to contact the server: 200 parsererror SyntaxError: Unexpected token < in JSON at position 2

Open in new window

0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41842736
Check the console look at the GET and expand it - you will see what came back from the server

Look at this line
$result['subtotal']->subtotal = number_format($value * $_SESSION['icms'.$prod], 2, '.', '')

Open in new window

Where are you defining $value?

Debugging
When working with AJAX you need to learn good debugging skills - you need to know how to use the console.

The error message you are getting is saying the return from the server was not valid JSON - that is because your PHP script generated an error - which it sent back. You can view this error in the console - knowing how to do this will save you hours.

Take a look at the image below
ss75.jpg
2
 

Author Comment

by:James Allan
ID: 41842796
i am using my console and i only get that error.

i  think im still doing something wrong.

$result['totals'] = new stdClass;
$value = $_SESSION[$prodname];
$result['subtotal']->subtotal = $value * $_SESSION['icms'.$prod]; /* subtotal result here */
$result['cost']->value = $_SESSION['icms'.$prod] ;/* Product cost here */
}

Open in new window


in my cart_functions.php

the quantity of product is stored in  $_SESSION[$prodname]
i.e:

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

Open in new window


and in this page my id has a diffrent name  $prod   = $_GET['prod_id'];
so as my dropdown script is document.ready a session starts on load.
so if there is a session called  $_SESSION['icms'.$id]; in my calculates.php
then my cart_functions.php  shall get  $_SESSION['icms'.$prod]; that is the same as  $_SESSION['icms'.$id];.
And in my calculates.php  $_SESSION['icms'.$id]; holds the cost .
So its supposed to be working.
obs:i am using google chrome console.

my plus and remove button works, but it does not update the values $value or the subtotal only if i refresh the page.
0
 

Author Comment

by:James Allan
ID: 41842811
The thing is you might had edited this

$result['totals'] = new stdClass;
$value = $_SESSION[$prodname];
$result['subtotal']->subtotal = $value * $_SESSION['icms'.$prod]; /* subtotal result here */
$result['cost']->value = $_SESSION['icms'.$prod] ;/* Product cost here */

Open in new window


and now i read you awnser again and now the code does not containe ->

so i did this
$result['totals'] = new stdClass;
$value = $_SESSION[$prodname];
$result['subtotal']= $value * $_SESSION['icms'.$prod]; /* subtotal result here */
$result['cost']= $_SESSION['icms'.$prod] ;/* Product cost here */

Open in new window


and now my $value that is my quantity of product updates again but still not the subtotal.
0
 

Author Comment

by:James Allan
ID: 41842818
So now i am getting this

ajax call returned the following: {"result":"success","val":11,"totals":{},"subtotal":445.94,"cost":"40.54"}

Open in new window

0
 

Author Comment

by:James Allan
ID: 41842852
Julian i know what was wrong.

It was my jquery , i didnt changed as you said to me.

so my code that updates the subtotal in cart_functions.php looks like this

$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 */  

Open in new window


and my script for the buttons and updating value ...
$('.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

0
 

Author Comment

by:James Allan
ID: 41842856
Julian thx for helping me today, you didnt give up at me, and i learned a lot with allmy mistakes today.
Bro you should make tutorials for youtube, how to do stuffs like this, i'm sure you will get lots of money with ads.

Thx for your patience, you are awesome.
0
 

Author Closing Comment

by:James Allan
ID: 41842859
You are the best!
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41843060
You are most welcome.
1

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

707 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

17 Experts available now in Live!

Get 1:1 Help Now