1

I have a web service which returns this JSON:

[{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

What I want is I want to populate it to some list and also want to get index of list item clicked so that I can retrieve more information according to that index value (user_id).

What I did is:

function fetchFunction() {
    //fn.load('fetchPage.html');
    console.log("fetchFunction is invoked");

    var header = "<ons-list-header>My Inset ListTTT</ons-list-header>";

    $.ajax({
        type: 'POST',
        url: "fetchJSON.php",
        timeout: 5000,
        //dataType:'text',
        dataType:'json',
        success: function(data) {
             var data2 = JSON.stringify(data); //to string
             //var data2 = JSON.parse(data); //to string
             console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2.user_name);         

             //alert("Index is: " + data[0]); 
             //$("#myListElement").html(header);
             //$("#myListElement").append(data);

             // Parse 'data' here
            console.log("SuccessED");
        },
        error: function(err) {
            ons.notification.alert("Error: " + err.status + ", " + err.statusText);
            console.log("Error: " + err);
            // console.log(err.status);
            // console.log(err.statusText);
            // $("#div1").text(err.responseText);
        }
    });
}

data2[0].user_id is doing nothing, just returning undefined.

I have a click function on that div called myListElement so I want to show the user_id on which the click function triggered.

if (event.target = "fetchPage2.html") {
        $("#myListElement").click(function(){
            alert("List Item Clicked!");
        });
    }

I will love if you give me some idea.

BTW I am using: Cordova + OnSenUI. :/

Thank You.

PS: I have this ons-list as a List. and want to populate it here.

<ons-list modifier="inset" id="myListElement">
    <ons-list-header >My Inset listdc</ons-list-header>
    <ons-list-item modifier="longdivider" tappable>Item A</ons-list-item>
    <ons-list-item modifier="longdivider" tappable>Item B</ons-list-item>
    <ons-list-item modifier="longdivider" tappable>Item C</ons-list-item>
</ons-list> 
3
  • 1
    you want to populate each user in each list-item tag ? Commented Apr 6, 2017 at 7:19
  • @warl0ck Aha Yeah. Each user in each list-item, when some user click on that list, so upon the user_id I will send request back to server and will open new activity which will be having detail page of that user. But I know many people don't use OnSenUI so they may not be able to help me in list-item ons-list. That's why I generalise my question. Commented Apr 6, 2017 at 7:22
  • You can get help from here: Unable to call function not getting page.matches OnSenUi Commented Apr 6, 2017 at 7:33

5 Answers 5

2

If your service returned data with application/json then use direct data variable

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);   

Test Code

var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);

If your service returned data with text then use convert data to Json with JSON.parse() function

var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);  

Test Code

var data = '[{ "user_id": "1", "user_name": "User1", "user_age": "20" }, { "user_id": "2", "user_name": "User2", "user_age": "21" }, { "user_id": "3", "user_name": "User3", "user_age": "24" }, { "user_id": "4", "user_name": "User4", "user_age": "34" }, {"user_id": "5","user_name": "User5", "user_age": "27" }]'
var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);

Sign up to request clarification or add additional context in comments.

4 Comments

I put dataType:'application/json', in my code and it's not accepting it. Can you please add more details, please?
Ok, you can use fiddler, charles or postman tool for test or watch requests and responses because, which data format returned your service?
It's JSON. I just did it with PHP's json_encode(); method. (The same data is returned as in my question)
Hmm, so you can use direct data[0].user_id without any convert.
1

With this small change your code works:

var data2 = JSON.stringify(data);
data2 = $.parseJSON(data2);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);      

Output: Index of list is: 1 and username is: User1

Demo: http://codepen.io/8odoros/pen/GWLmwB

3 Comments

Why I was unable to use data before and after using data2 = $.parseJSON(data2); I can use it. Can you please explain it little bit? and what If I use dataType: 'text', ?
@fWd82, I suppose you mean data2 not data. Before $.parseJSON(data2) data2 is just a string. After that it's an object so you can use data2[0] to get the properties of the first child.
So I use: var data2 = JSON.parse(data); by replacing: var data2 = JSON.stringify(data); data2 = $.parseJSON(data2); and great it's working. Looks like they are interchangeable.
1
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
    var myJSON = [{     "user_id": "1",     "user_name": "User1",     "user_age": "20" }, {     "user_id": "2",     "user_name": "User2",     "user_age": "21"              }, {     "user_id": "3",     "user_name": "User3",     "user_age": "24" }, {     "user_id": "4",     "user_name": "User4",     "user_age":              "34" }, {     "user_id": "5",     "user_name": "User5",     "user_age": "27" }];
    function fetchFunction(){
        $('#myListElement tbody').empty();
        $.each(myJSON,function(ind,obj){
            var htmlTemplate = "<tr userID=" + obj.user_id + " onClick='displayUserData(this)'><td></td><td>" + obj.user_id + "</td><td>"+ obj.user_name +"</td><td>"+ obj.user_age +"</td></tr>"
            $('#myListElement').append(htmlTemplate);
        });
    }
    function displayUserData(ref){
        myTr = ref;
        alert("User ID :: "+ $(ref).attr('userID') +" Row is Click");
    }
</script>
<input type="button" onClick="fetchFunction()" value="Fetch Data">
<table id="myListElement" border="1" cellspacing="0" cellpadding="10">
    <thead>
        <th>My Inset listdc</th>
        <th>Item A</th>
        <th>Item B</th>
        <th>Item C</th>
    </thead>
    <tbody>

    </tbody>
</table>

1 Comment

Thank You @Kinjal, You code helps clear confusion and help me alot getting idea. :)
1

After using the command JSON.stringify() function its no longer a array that you can access, If you are getting JSON object from the server you can directly access as objects like data[someindex].user_id.

If you are getting the data as string in that case you can use data = JSON.parse(data) Here is JSFIddle sample

To get the User details on clicking the user:

var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]
success(data);
function success(data) {
    console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);
    for(var i=0;i<data.length;i++) {
        $("#myListElement").append('<ons-list-item>' + data[i].user_name + '</ons-list-item>');

    }
}

$("#myListElement").on('click', 'ons-list-item', function() {
var index = $(this).index();
	console.log('selected user details: name:  ' + data[index].user_name + '  id: ' + data[index].user_id + '  age : ' + data[index].user_age);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ons-list modifier="inset" id="myListElement">

</ons-list> 

Here is JSfiddle link as well.

8 Comments

Why the first JSfiddle is having Uncaught SyntaxError: Unexpected token o in JSON at position 1 ? Looks like we are parsing it again?
my bad, here the error is coming because the data is already in JSON format so no point in parsing. this is in case if you get data in string format from server, if you are getting object then just comment it out
In JSfiddle example my data is in object format not string, and as in my answer what I meant is you should not use JSON.stringify()
Happy to help, BWT you can upvote/+1 more than one answer but can accept only one by selecting the tick below upvote.
the JSON data coming is object itself, same as I declared in the example, generally you will be getting JSON data only therefore you wont require to parse it.
|
0

You can parse json using $.parseJSON() function. Please check example given below:

$( document ).ready(function() {
        var data = '[{"user_id": "1","user_name": "User1","user_age": "20"}, {"user_id": "2","user_name": "User2","user_age": "21"}, {"user_id": "3","user_name": "User3","user_age": "24"}, {"user_id": "4","user_name": "User4","user_age": "34"}, {"user_id": "5","user_name": "User5","user_age": "27"}]';  
        var data2 = $.parseJSON(data);
                console.log("Print json data");
                  $.each(data2, function(i, item) {
                        console.log("Index of list is: " + item.user_id + " and username is: " + item.user_name + " and age is: " + item.user_age);      
                  });                        
                console.log("End print");
        });

Comments

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.