cyprian cyprian - 7 months ago 26
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) {
items.push(val);
})
$("#cartbox").text(items[0]);
return items[0];
});
};


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

Answer

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 data.name to get the returned count.

With those issues in mind, try this:

function updateQuantity(){ 
    // code...
    updateCart();
    // code...
}

function updateCart() {
    $.getJSON('@Url.Action("GetCartCount", "Cart")', function(data) {
        $('#cartbox').text(data.name);
    });
}
Comments