0

basically my goal is to get all the json values into javascript / jquery variable so that i can show them on my html input fields. I am beginner in javascript so i cannot identify what i am doing wrong. Below is my function

 // Update existing customers 
                $("#records").on('click', ".update", function() {
                    var data = $(this).attr('id');
                    var object = {};
                    $.ajax({
                        type: "GET",
                        url: "viewcustomers.php",
                        data: {update: data},
                        success: function(response) {
<!--                           console.log(response);-->
                           object = $.parseJSON(response);
                           console.log(object.name);

So when i run this function i get a json response in my success: like below

"[{"id":"1","name":"ali","cnic":"01","address":"nipa","email":"301","phone":"luxairy "}]"

Now as per my understanding i tried to parse the response via jquery and take it in object. But when i am trying to console.log name or any other value its saying undefined.

Please help me understanding what i am doing wrong. Thank you. } });

1
  • [] indicates that you get an array (with 1 element in this exact case), as you can see here - json.org Commented Jan 7, 2014 at 10:35

1 Answer 1

4

You have to get object from array, the square brackets [] in begining and end make the the json object an array of objects. You need to use array indexer notation. Remember it is zero-index that means first element is at zero index.

Change

object.name

To

object[0].name

Edit, based on commments, to iterate through object array you can use loop.

for(i=0; i < object.length; i++) 
    console.log(object[i].name);
Sign up to request clarification or add additional context in comments.

5 Comments

[0] means ? is it necessary to have a numeric index ?
It is array indexer notation. Remember it is zero-index that means first element is at zero index.
worked thank you so much ... it means if i have more rows in JSON so i will have to use indexes right ?
Yes, you can use loop to iterate through them
for(i=0; i < object.length; i++) console.log(object[i].name);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.