1

Below listed is my json response. My purpose is to get this data in javascript. My firebug console shows below result. Please help me to get data in js.

{"ProfessionFile":[[{"id":34,"title_en":"CEO"}],[{"id":35,"title_en":"PM"}]]}

Alert shows "undefined" result JS

$(".tag-handler-ambition").ready(function () {
    $.get("/profession/file", {tagcategoryid: 3}, function (response) {
            for (var i = 0; i < response.ProfessionFile.length; i++) {
                alert(response.ProfessionFile[i].id);
                $(".tag-handler-ambition").after('<div id="filename-response_' + response.ProfessionFile[i].id + '"><a href="/profession/download/' + response.ProfessionFile[i].id + '">' + response.ProfessionFile[i].title_en + '.pdf</a></div>');
            }
    });
});

1 Answer 1

2

You should parse this response as a JSON, othewise JavaScript will not see it as an object:

$(".tag-handler-ambition").ready(function () {
    $.get("/profession/file", {tagcategoryid: 3}, function (response) {
        response = $.parseJSON(response);
        for (var i = 0; i < response.ProfessionFile.length; i++) {
            $(".tag-handler-ambition").after('<div id="filename-response_' + response.ProfessionFile[i].id + '"><a href="/profession/download/' + response.ProfessionFile[i].id + '">' + response.ProfessionFile[i].title_en + '.pdf</a></div>');
        }
    });
});
Sign up to request clarification or add additional context in comments.

5 Comments

I have added this. But showing some error "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data " for (var i = 0; i < response.ProfessionFile.length; i++) { var obj = $.parseJSON( response.ProfessionFile[i].id ); alert(obj); }
I have updated my answer to reflect your entire code. Can you take a look?
I have added your code but showing an error "SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data". For avoiding this I have added "response = JSON.stringify(response);" before parseJSON. Now alert showing [undefined].
$(".tag-handler-ambition").ready(function () { $.get("/profession/file", {tagcategoryid: 3}, function (response) { response = JSON.stringify(response); response = $.parseJSON(response); for (var i = 0; i < response.ProfessionFile.length; i++) { alert(response.ProfessionFile[i].id); $(".tag-handler-ambition").after('<div id="filename-response_' + response.ProfessionFile[i].id + '"><a href="/profession/download/' + response.ProfessionFile[i].id + '">' + response.ProfessionFile[i].title_en + '.pdf</a></div>'); } }); });
I don't know why it's not working. Could you try $.getJSON? api.jquery.com/jquery.getjson

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.