Sk Asraf Sk Asraf - 5 months ago 11
JSON Question

how can take value from ajax request?

some of the resign i cant take value from ajax, where json data is comming like that

enter image description here
request

i wan to take value from ReviewPoint and after that manupulate some other jquery in ajax success block.

but problem is i cant take value when i trying to print value using alert box it showing "undefine"

my jquery code is

var productid = $("#productid").text();
$.ajax({
url: '/ProductService/CheckUserExistFirst.asmx/rating',
method: 'GET',
// dataType: 'json',
data: { productid: productid },
//contentType: "application/json; charset=utf-8",
success: function (data) {

alert(data.d.ReviewPoint);
if (data.ReviewPoint < 1) {
$("#rat-1").removeClass("fa fa-star-o");
$("#rat-1").addClass("fa fa-star");
}
if (data.ReviewPoint < 2) {
$("#rat-1,#rat-2").removeClass("fa fa-star-o");
$("#rat-1,#rat-2").addClass("fa fa-star");
}
if (data.ReviewPoint < 3) {
$("#rat-1,#rat-2,#rat-3").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3").addClass("fa fa-star");
}
if (data.ReviewPoint < 4) {
$("#rat-1,#rat-2,#rat-3,#rat-4").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3,#rat-4").addClass("fa fa-star");
}
if (data.ReviewPoint < 5) {
$("#rat-1,#rat-2,#rat-3,#rat-4,#rat-5").removeClass("fa fa-star-o");
$("#rat-1,#rat-2,#rat-3,#rat-4,#rat-5").addClass("fa fa-star");
}
},
error:function(err){
alert(err);
}
})

Answer

The response is an array so you need to access it by index using array notation. There is also no d property in the response. Try this:

var reviewPoint = data[0].reviewPoint;

Also note that you can DRY up your code by giving all the #rat-N elements a common class. You can then use eq() and prevAll() to set the classes on the required elements. Try this:

success: function (data) {
    var reviewPoint = data[0].reviewPoint;

    $('.rat').eq(reviewPoint).prevAll('.rat').addBack().removeClass('fa-star-o').addClass('fa-star');
});
Comments