2

I'm trying out some jQuery / AJAX tutorials; specifically this one: https://www.youtube.com/watch?v=fEYx8dQr_cQ

He has is external API returning the following JSON (and it works!):

[
  {
    name: 'john',
    drink: 'coffee'
  },
  {
    name: 'jack',
    drink: 'latte'
  }
]

But when I try that locally (running http-server) I keep getting errors saying:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [
  {
   name: 'john',
   drink: 'coffee'
  },
  {
   name: 'jack',
   drink: 'latte'
  }
 ]

But when I put everything in double quotes, I no longer get any errors (makes sense, since now it is valid JSON):

[
 {
  "name": "john",
  "drink": "coffee"
 },
 {
  "name": "jack",
  "drink": "latte"
 }
}

The next issue then was that my code doesn't get any of the data. I then learned that I had to add the option dataType = "JSON" for it to work, while the video did not have to do that.

Why is this the case?

var $content = $( '.content' );

$( function () {
 $.ajax( {
  type: 'GET',
  url: './orders.api.js',
  success: function( data ){
   console.log(data);

   $.each( data, function( index, order ) {
    $content.append( '<li>' + order.name + ' likes ' + order.drink + '</li>' );
   });
  }
 });
});
<div class="content">
 <ul></ul>
</div>

I'm getting confused as to why everything works in the video, but when I copy it exactly it does not work for me.

How did he have a API returning JSON with single quotes? How did he not have to use dataType='JSON'?

sjmartin
  • 3,912
  • 4
  • 19
  • 32
  • Not a duplicate. Updated question to ask how the tutorial was able to pass JSON with single quotes. – sjmartin Mar 04 '16 at 22:29
  • Your question is based on a false premise. If you look at the actual response (in the browser window in the video), it is properly formatted JSON. The single quotes only appear in the "Sample Response" (which isn't actually used for anything). – Quentin Mar 04 '16 at 22:33
  • @Quentin Then it's not a duplicate, it's just a question that assumes something that is not true and can be closed as not a real question, like typos? – Ruan Mendes Mar 04 '16 at 22:35
  • 1
    @Quentin Ah damn't, I see that now. That response was such a short blip in the video that I didn't catch that. Confusing sample data when trying to learn I guess. The "response" he shows actually isn't JSON. Wonder why he formatted it that way. Thanks! – sjmartin Mar 04 '16 at 22:39

0 Answers0