-4

I receive this as a response from an ajax call. My question is how can I get the values of the object?

{"countries":[{"country_id":730,"country":"El Salvador"},{"country_id":756,"country":"Guatemala"},{"country_id":767,"country":"Indonesia"}]}

my ajax call is this:

$.ajax({
    type: "POST",
    dataType:"json",
    url:getCountriesPackages,
    data: "transferUrl=countries?service_id="+serviceId,
    success: function(data) {

        $.each(data, function(k, v) {
          console.log(k);
        });
    }
});

thank you

  • `json_decode`, http://php.net/manual/en/function.json-decode.php – Goose Jul 11 '17 at 13:13
  • First of all, `php` tag is not what you want. You say I *receive*, so this is happening in the browser, hence javascript. Then, it depends on how you make the ajax call. If you are using a jquery family of ajax calls, you are passing it a callback function that receives the object when the call is complete. – Majid Fouladpour Jul 11 '17 at 13:17
  • Help us help you. Post the code you currently use to make the ajax call. It's not that difficult. – Majid Fouladpour Jul 11 '17 at 13:21

2 Answers2

0

You already have a JSON, you can traverse it using $.each():

var obj = {
  "countries": [{
    "country_id": 730,
    "country": "El Salvador"
  }, {
    "country_id": 756,
    "country": "Guatemala"
  }, {
    "country_id": 767,
    "country": "Indonesia"
  }]
};

$.each(obj, function(k, v) {
  $.each(v, function(kk, kv) {
    console.log("Country ID: " + kv.country_id);
    console.log("Country: " + kv.country);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0

Your response is a JavaScript object. We access attributes via the dot operator. Our first attribute returned is of type array. You can iterate through the array and access its' attributes for each element.

var response = {"countries":[{"country_id":730,"country":"El Salvador"},{"country_id":756,"country":"Guatemala"},{"country_id":767,"country":"Indonesia"}]};
var countries = response.countries;
for(var i = 0; i < countries.length; i++)
{
    var country_id = countries[i].country_id;
    var country = countries[i].country;
}
MackProgramsAlot
  • 583
  • 1
  • 3
  • 16