James Allan
asked on
jquery is not updating my php value when user selects dropdown option
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...
this is where i am trying to update when user select his product options
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.
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.
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);
});
}
}
});
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>
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
}
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.
ASKER
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
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);
And now all my values is displaying R$:undefined
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
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
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)
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);
});
Inspect the console and see what the return from the GET is. Post that here.
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 . '">';
you would haveecho <<< CELL
<td class="product" id="product_{$id}">
CELL;
HEREDOC allows you to mix double and single quotes as well as embed variables.
ASKER
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;
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.
You still need to post the results of the console.log(data) I asked for in my earlier post.
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;
You still need to post the results of the console.log(data) I asked for in my earlier post.
ASKER
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.
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.
ASKER
Julian in my console shows only the cost based on my dropdown selection.
When used console.log
When used console.log
Can you post the console output.
In your code you have this
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.
In your code you have this
}).done(function(data) {
$('.cost' + id).text(data.val);
$('.subtotal' + id).load(data.val);
});
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.
ASKER
well 'im sorry, i didnt said that i used the fixed code that you provided.
this one in giving me the R$:undefined.
$('.cost[data-id=' + id + ']').html('R$:' + data.val);
$('.subtotal[data-id=' + id + ']').html('R$:' + data.val);
this one in giving me the R$:undefined.
I still need to see the return from the GET - we are going to get nowhere unless you post that.
ASKER
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
But something is still not making sense - in your PHP code your subtotal is worked out like this
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?
.done(function(data) {
$('.cost[data-id=' + id + ']').html('R$:' + data);
$('.subtotal[data-id=' + id + ']').html('R$:' + data);
});
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>
$value * $_SESSIONBut 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?
ASKER
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
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.
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>
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.
ASKER
i change my code to this.
$subtotal=$value * $_SESSION['icms'.$id];
$cost=$_SESSION['icms'.$id];
<td class="cost" data-id="'.$id.'" >'.$cost.'</td>
<td class="subtotal" data-id="'.$id.'">'.$subtotal .'</td>
ASKER
look a made a video to explain whats going on.
https://youtu.be/V6H4rqgFr40
https://youtu.be/V6H4rqgFr40
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
Did you try this
.done(function(data) {
$('.cost[data-id=' + id + ']').html('R$:' + data);
$('.subtotal[data-id=' + id + ']').html('R$:' + data);
});
ASKER
Yes i am Julian
ASKER
My cost is $_SESSION['icms'.$id] and the value will multiply: $value X $_SESSION['icms'.$id].
So what you suggest to me fix this?
So what you suggest to me fix this?
This is PHP not JavaScript
You are making an AJAX call back to the server here
Either you need to send back the cost and total in a JSON structure
Example
But before we get there - the original problem was that
Is this still giving undefined
$value X $_SESSION['icms'.$id].
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
});
}
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));
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);
});
Note the change from data.val to data.
ASKER
Yeah now it worked and as you said cost and subtotal are the same value.
Look this generates my costs
calculate.php....
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]);
}
echo json_encode( $_SESSION['icms'.$id]);
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));
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);
});
ASKER
I fixed like this...
In my calculate.php
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.
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
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
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.
$('.cost[data-id=' + id + ']').html('R$:' + data.cost);
$('.subtotal[data-id=' + id + ']').html('R$:' + data.subtotal);
but now my cost is displaying i.e 1 or 2 or 3I 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];
So do i have to include my cart.php in calculates.php?
ASKER
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));
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?
Is it working now?
ASKER
Yes now its working!!!
When i did the last thing you said it didnt work because this...
Now to finalize it i need to make my subtotal update when i click on plus and minus buttons.
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));
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'])){
So it worked =DNow to finalize it i need to make my subtotal update when i click on plus and minus buttons.
ASKER
$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>';
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?
ASKER
Look what i did to make my buttons update my subtotal
i created
and on .done(function(data)){.. i put a IF.
but this didnt work.
i created
var action = $(this).attr('data-action');
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);
}
});
but this didnt work.
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
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.
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);
});
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.
ASKER
this is my cart_functions.php this handles all my buttons
and this works on my second jquery script
<?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'];
}
and this works on my second jquery script
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.
Right now you are returning the val only - expand your return array to include the subtotal and product cost.
ASKER
Sorry man i don't have a clue what to do now.
Because what handles my buttons is
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);
}
});
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
and it didnt work, and my plus and remove stopped working.
check the urls from both scripts
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 */
.and it didnt work, and my plus and remove stopped working.
check the urls from both scripts
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.
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.
ASKER
look how is my code now
if i remove:
the error i got when i used the code above
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);
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 */
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
i am using my console and i only get that error.
i think im still doing something wrong.
in my cart_functions.php
the quantity of product is stored in $_SESSION[$prodname]
i.e:
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.
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 */
}
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]];
}
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.
ASKER
The thing is you might had edited this
and now i read you awnser again and now the code does not containe ->
so i did this
and now my $value that is my quantity of product updates again but still not the subtotal.
$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 */
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 */
and now my $value that is my quantity of product updates again but still not the subtotal.
ASKER
So now i am getting this
ajax call returned the following: {"result":"success","val":11,"totals":{},"subtotal":445.94,"cost":"40.54"}
ASKER
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
and my script for the buttons and updating value ...
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 */
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);
});
});
ASKER
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.
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.
ASKER
You are the best!
You are most welcome.
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
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
Open in new window
Again this line confuses me
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
Open in new window
The same would apply to these lines
Open in new window