cyprian cyprian - 5 months ago 11x
Javascript Question

How to retrieve response from JSON to simple type

I have problem to retrieve an int value from a JSON response. Here is my code:

public ActionResult GetCartCount()
int caounofcart = shoppingCartManager.GetCartItemsCount();
return Json(new { name = caounofcart });

function updateQuantity() {
// code...
$("#cartbox").text(updatecart); // here is span element
// code...

function updatecart() {
$.getJSON("@Url.Action("GetCartCount", "Cart")", function(data) {
var items = [];
$each(data, function (key, val) {
return items[0];

I want to change text content in the
element through the JSON response. How can I do that?


Firstly you cannot achieve this using the logic you specify as the AJAX request is asynchronous. This means that the updatecart() function will have exited long before any data is returned from the request, so no value will be provided to text().

Secondly, you only return a single integer value in the JSON response so you can simply use to get the returned count.

With those issues in mind, try this:

function updateQuantity(){ 
    // code...
    // code...

function updateCart() {
    $.getJSON('@Url.Action("GetCartCount", "Cart")', function(data) {