4

the response comes back as "4" instead of just 4

I tried changing it to .done(function(data)) but still has the same result

 $.ajax({ url: "../api/ajax/addToCart.php", type: "post", data: data }) .done(function(response) { // alert(response); $('#cart_counter').html(response); // console.log(JSON.parse(response)); getCart(); // console.log(response); }); 

the ajax is taking the response from this page addToCart.php

$sql1 = 'DELETE FROM temp_cart WHERE item_id = "' . $item_id . '" AND temp_id = "' . $temp_id . '"'; $result = $conn->query($sql1); { $sql2 = 'INSERT INTO temp_cart(temp_id, temp_name, temp_number, item_name, item_price, item_quantity, item_total, item_pic, item_id, date_expiry) VALUES ("' . $temp_id . '", "' . $temp_name . '", "' . $temp_number . '", "' . $item_name . '", "' . $item_price . '", "' . $item_quantity . '", "' . $total_row . '", "' . $item_pic . '", "' . $item_id . '", "' . $date_expiry . '" )'; $result = $conn->query($sql2); { $sql = "SELECT count(item_quantity) as count_quantity FROM temp_cart WHERE temp_id='$temp_id'"; $resultb = $conn->query($sql); while($rowb = $resultb->fetch_assoc()) { $cart_counter=$rowb['count_quantity']; echo json_encode($cart_counter); } } } 
5
  • What are you sending from the server? Sounds like an extra stringify() somewhere. Commented Nov 23, 2019 at 1:18
  • 1
    @zipzit updated the question, please have a look Commented Nov 23, 2019 at 1:20
  • I’m thinking server side php. Where do you send the $cart_ quantity back to client as a response? json_encode ?? Commented Nov 23, 2019 at 1:24
  • 1
    @zipzit yes, json_encode Commented Nov 23, 2019 at 1:27
  • 1
    This is answer to my question. Commented Nov 23, 2019 at 2:45

1 Answer 1

1

The data not really JSON format, but a number that is being stringified when you pass it back as JSON so it ends up a string. Just parse the string into a number as needed:

 $('#cart_counter').html(parseInt(response)); 

let counter = 4; let json = JSON.stringify(counter); console.log(json, `is a ${typeof json}`); console.log(`...now a ${typeof parseInt(json)}`); document.querySelector('#target').innerHTML = parseInt(json);
<div id="target"></div>

Sign up to request clarification or add additional context in comments.

14 Comments

it is now displaying nothing. no error can be seen in console
it says "8" string
it says "8" with the quotations
it now says "number" with the quotations
but it still displays with the quotation marks on my element
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.