1

I am using Struts2 and ajax. Ajax get function returns a json. But, if I print the returned json using "alert" or console, it shows [object, Object]. I have used dataType:"json" in the ajax call too. Can someone please point out what could be missing?

$.ajax({
        type:"GET",
        data: "searchClientPhone=" + searchClientPhone,
        url: "searchClientCellPhoneNo",
        dataType: "json",
        headers : {
            Accept : "application/json; charset=utf-8", 
            "Content-Type" : "application/json; charset=utf-8"
        },
        success: function(result){

        alert("result: " + result);
        /* var response = $.parseJSON(result);
        alert("response is  : " + response);
        console.log("Response : " + response); */
        console.log("Result " + result);

        $("#selectedClientName").html(result.selectedClientName);
    $("#selectedClientRewardPoints").html(result.selectedClientRewardPoints);
            $("#progressbar").hide();
            $("#example td").each( function() {
                 var thisCell = $(this);
                 var cellValue = parseInt(thisCell.text());

                 if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
                     thisCell.css("background-color","#FF0000");
                  }
              }
             );

            $("#selectedClientName").show();        
            $("#selectedClientRewardPoints").show();

        }
    }); 

I have even tried using parseJSON but it gives me an error "unexpected token o" which on searching seems to be error if the returned result is already parsed.

Thanks in advance!

1 Answer 1

3

You need to stringify your JSON to view it in an alert.

alert("response is  : " + JSON.stringify(response));
Sign up to request clarification or add additional context in comments.

2 Comments

I just tried that, it works. But, to use it further after alert(to put the data from json in text fields), should I assign the stringified version to another var and use?
No, the 'stringified' version is just the JSON string. If you want to easily access the properties with dot notation, you'll want to keep it as the JSON object you received from the request.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.