0

I am using CodeIgniter. In my Controller file, I have JSON containing an array (as a result of calling different API's):

{
    "Specialities": [{
        "SpecialityID": 1,
        "SpecialityName": "Eye Doctor"
    },{
        "SpecialityID": 2,
        "SpecialityName": "Chiropractor"
    },{
        "SpecialityID": 3,
        "SpecialityName": "Primary Care Doctor"
    }] 
}

In controller, I wrote

echo $response[0];

with this line of code I can easily iterate through json object in jquery:

$.ajax({
    type: 'GET',
    url: 'http://localhost/rest_project/main/res',
    dataType: 'JSON',
    crossDomain: true,
    xhrFields: { withCredentials: true },
    success: function (data){
        $.each(data.Specialities,function(key,value){
            console.log(value.SpecialityName);
        });
    }  
});

but if I pass the array:

echo json_encode($response); 

Then I am unable to get the results:

$.ajax({
    type: 'GET',
    url: 'http://localhost/rest_project/main/res',
    dataType: 'JSON',
    crossDomain: true,
    xhrFields: { withCredentials: true },
    success: function (data){
        $.each(data[0].Specialities,function(key,value){
            console.log(value.SpecialityName);
        });
    }
});

Can someone help me please?

1 Answer 1

2

It seems that your jsonObject is not an array and each works with array only.

//Check if your jsonObject is array, if not then make it.
if (!$.isArray(jsonObject)) {
    jsonObject = [jsonObject];
}

$.each(jsonObject, function(key, value){
  console.log("FULL NAME " + value.FullName);
});

var data = {
    "Specialities": [{
        "SpecialityID": 1,
        "SpecialityName": "Eye Doctor"
    },{
        "SpecialityID": 2,
        "SpecialityName": "Chiropractor"
    },{
        "SpecialityID": 3,
        "SpecialityName": "Primary Care Doctor"
    }] 
};
//Convert your jsonObject to array for each
if (!$.isArray(data)) {
    data = [data];
}
$.each(data[0].Specialities,function(key,value){
   console.log(value.SpecialityName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

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.