SDH
SDH

Reputation: 391

Can't call individual value from key : value pair using Jquery

For some odd reason, I am unable to successfully call a value from it's key using JQuery. Is there some error in my syntax or what I am doing wrong?

If I output the function "data" to console.log, I get the following:

{"maxFileSize" : "10 MB", "fileList" : [{"fileName" : "FVI-500_Installation", "href" : "../Docs/FVI-500_Installation.pdf","uploadDate" : "06/14/2016","fileSize" : "1.5 MB"}]}

My HTML and Javascript:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="randominfo"></div>

<script>

    $.getJSON('http://localhost/MISREST/helpdocs', function (data) {
  $.each( JSON.parse(data), function ( key, val ) {
    $("#randominfo").append(val.maxFileSize);

  });
    });

</script>

Upvotes: 0

Views: 58

Answers (1)

Christoph
Christoph

Reputation: 51201

Your code is overly complicated. Try the following changes:

1) You don't need to call JSON.parse, jQuery already does this for you.

2) since you already get an object back, all you need is use data.maxFileSize, no need for a loop

3) use the Promise methods, as this allows for cleaner code, see also the official docs.

$.getJSON('http://localhost/MISREST/helpdocs')
 .done(function( data ) {
     // this is the success case
     $("#randominfo").append(data.maxFileSize);
  })
 .fail(function() {
     // this is the error case
     console.log( "an error occured" );
  })
 .always(function() {
     // as the name implies, this is always executed once the request returned
     // regardless of its state. Often you won't need this.
     console.log( "the request was completed" );
  });

The minimal change to your code would be the following:

$.getJSON('http://localhost/MISREST/helpdocs', function (data) {
    $.each( JSON.parse(data), function ( key, val ) {
       if (key === "maxFileSize")
           $("#randominfo").append(val);
    });
});

Upvotes: 4

Related Questions