Question

Using the Plivo api, I am making a getJSON call, so the following is returned:

[
  {
    "group_id":"31505537702425",
    "number_type":"local",
    "prefix":"347",
    "region":"New York, UNITED STATES",
    "rental_rate":"0.80000",
    "resource_uri":"/v1/Account/MAMTE4MTHJNJRKODBIMD/AvailableNumberGroup/31505537702425/",
    "setup_rate":"0.00000",
    "sms_enabled":true,
    "sms_rate":"0.00450",
    "stock":46,
    "voice_enabled":true,
    "voice_rate":"0.00850"
    }
]

I can access it with this["region"], for example, which allows me to print New York, UNITED STATES. No problem.

But with this array:

{
    "api_id":"2653f0d4-c4a3-11e3-9c37-22000ac7849b",
    "message":"created",
    "numbers":[
      {
        "number":"13474749242",
        "status":"Success"
      }
    ],
    "status":"fulfilled"
}

the same approach, this["number"]returns "undefined.

The full code is:

function buy_number(id) {
       $("#results").html('')
       $("#results").html('renting your number.... hang on a sec');
        var group_id = id;
        $.getJSON("/rentnumber?group_id="+group_id, function(data) {
          $.each( data, function( key, value ) {
          $("#results").html("");
          $("#results").append('<p>You just bought '+this["number"]+'</p>');
                     });
               });
        }

It works, the number is bought but I cannot display the result on the user page. all help appreciated as always.

Was it helpful?

Solution

Just do:

this.numbers.number

or

this["numbers"].number

instead of what you are doing

OTHER TIPS

You can use:

$.each(data.numbers, function (key, value) {
    $("#results").html("");
    $("#results").append('<p>You just bought '+this["number"]+'</p>');
});

Fiddle Demo

You will need to do:

this["numbers"][0]["number"];

As "numbers" is an array not an object so you need the first array element of numbers.

below will work even if you have multiple items in numbers array Demo

              var i=0;
              $.each(data,function(index,item){  
              alert(item.numbers[i].number);
              i++;
              });

You have to use

    this["numbers"]["number"]

because number is inside numbers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top