简体   繁体   中英

remove quotation mark in ajax response

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM