Eliminate the use of quotation marks in the AJAX response

The response returned as "4", instead of just 4

I attempted changing it to .done(function(data)) but the outcome remained the same

$.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 call is fetching the response from the 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);
            }
    }
}

Answer №1

The information is not exactly in JSON format, instead it is a number that gets converted to a string when passed back as JSON. To convert it back to a number, simply parse the string:

 $('#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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Comparing the methods of retrieving JSP data in a servlet: using BufferedReader with request.getInputStream() versus using request.getParameter

Here is an example of my ajax call: $.ajax({ url: '/bin/commersenext/assetUpload', type: 'POST', contentType:'application/json', data: JSON.stringify(ob), dataType: ...

Error: The function expressJwt is not recognized as a valid middleware

As I delve into learning about middlewares, I encountered an issue when trying to import express-jwt. The syntax I used was: const expressJwt = require('express-jwt') To address the problem, I uninstalled the current version of express-jwt and i ...

Accurate representation of a JavaScript object using Node.js Express

I have a certain structure that I need to display on my JADE page, so I created a JSON-like object to store the data. This is how the JSON object looks like : var dataSet1 = { meta: { "name": "Some text", "minimum": mini_2, "ma ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

Updating file extension name in ReactJS: A quick guide

Looking to modify a file name and extension within the react.js public folder. Changing index.html to index.php https://i.stack.imgur.com/zp1Ga.jpg ** ...

Choosing a request date that falls within a specified range of dates in PHP Laravel

In my database, I currently store two dates: depart_date and return_date. When a user is filling out a form on the view blade, they need to select an accident_date that falls between depart_date and return_date. Therefore, before submitting the form, it ne ...

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...

Angular.js fails to load successfully every other time

My angular application is running into some issues with bower. At times, when I start up the server, I encounter the following error: Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:modulerr] Failed to in ...

Retrieve JSON information utilizing a specific value stored in the localStorage

After an extensive search online yielded no results, I decided to seek assistance here. This is what I have managed to gather so far: JSON I possess a JSON file containing various lists of words that require retrieval based on user input. The structure ...

No error reported upon trying to render json output

I'm having an issue where the following code is not displaying any output. Can someone help me identify what mistake I might be making? This is the HTML file: <head> <script type = "text/javascript"> function ajax_get_json() { var h ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

Guide on reusing javascript to toggle between image sources

I have a simple website with buttons that, when clicked, change the image being displayed. However, I find myself repeating code for each button, and I'm wondering if there is a more efficient solution to this problem. Here is an example of what I cu ...

Graph is vanishing while linked

A unique HTML canvas is included in a standalone file called dashboard.html. To display the dashboard on the main homepage (home.html), we utilize ng-view nested within an ng-if directive. Oddly, clicking on the hyperlink "#" from the home page causes th ...

Showcase pictures from a directory in real-time using a combination of jQuery and Bootstrap as the folder continues to fill up with images

Although I am just beginning to learn about UI, I have a question that seems important to me. In my application, there is a background thread that downloads images and saves them in a folder named "images". I want these images to be displayed in the UI as ...

I am curious about how to implement overflow:hidden along with position:sticky in React.js

My attempt to address the white space issue caused by a navbar I created led me to try using overflow:hidden. The navbar is generated using the Header component, and I desired for it to have a position: sticky attribute. However, I realized that I cannot ...

Using ajax to send an array to PHP

I have an array named "heart" that is being sent via ajax... var heart = [31,32,33,34,35,36,37,38,39,42,43]; // Sending this data via ajax to php file/ $.ajax({ type: "POST", data:{ 'system': heart }, url: "login-function.php", success: f ...

Is there a way to transform JSON text into a JSON object?

Similar Question: How do I convert JSON to a JavaScript object? { "data": [ { "name": "JoongBum Lee", "id": "526210623" }, { "name": "\uc774\uc778\uaddc", ...

What is the process for dynamically setting @click in vue.js?

My array contains objects with methods as actions from a vue object. How can I dynamically set the @click event in a v-for loop? I attempted to use this.m1, "this.m1", "m1", but encountered an error: fns.apply is not a function. Javascript: new Vue ...

Unable to fetch a new session from the selenium server due to an error

I'm currently in the process of setting up Nightwatch.js for the very first time. I am following the tutorial provided at this link: https://github.com/dwyl/learn-nightwatch Unfortunately, I have encountered a barrier and require assistance to resolv ...