{ "name": "JSON APIs and Ajax", "order": 10.5, "time": "2h", "challenges": [ { "id": "bb000000000000000000001", "title": "Trigger Click Events with jQuery", "description": [ "In this section, we'll learn how to get data from APIs. APIs - or Application Programming Interfaces - are tools that computers use to communicate with one another.", "We'll also learn how to update HTML with the data we get from these APIs using a technology called Ajax.", "First, let's review what the $(document).ready() function does. This function makes it so all code inside of it only runs once our page loads.", "Let's make our \"Get Message\" button change the text of the element with the class message.", "Before we can do this, we need to implement a click event inside of our $(document).ready() function by adding this code:", "$(\"#getMessage\").on(\"click\", function(){", "", "});" ], "tests": [ "assert(code.match(/\\$\\s*?\\(\\s*?(?:'|\")\\#getMessage(?:'|\")\\s*?\\)\\s*?\\.on\\s*?\\(\\s*?(?:'|\")click(?:'|\")\\s*?\\,\\s*?function\\s*?\\(\\s*?\\)\\s*?\\{/gi), 'message: Bind the click event to the button with the ID of getMessage');", "assert(code.match(/\\n*?\\s*?\\}\\n*?\\s*?\\);/gi) && code.match(/\\n*?\\s*?\\}\\);/gi).length >= 2, 'message: Be sure to close your functions with });');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", " // Only change code below this line.", " ", " // Only change code above this line.", " });", "fcces", "", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Activa eventos de pulsación con jQuery", "descriptionEs": [ "En esta sección, vamos a aprender cómo obtener datos de las APIs. Las APIs - o interfaces de programación de aplicaciones - son herramientas que utilizan los computadores para comunicarse entre sí.", "También aprenderemos cómo actualizar HTML con los datos que obtenemos de estas API usando una tecnología llamada Ajax.", "En primer lugar, vamos a revisar lo que hace la función $(document).ready(). Esta función hace que todo el código dentro de ella se ejecute sólo hasta que nuestra página ha sido cargada.", "Hagamos que nuestro botón \"Get message\" cambie el texto del elemento con clase message.", "Antes de poder hacer esto, tenemos que implementar un evento de pulsación dentro de nuestra función $(document).ready(), añadiendo este código:", "$(\"#getMessage\").on(\"click\", function(){", "", "});" ] }, { "id": "bc000000000000000000001", "title": "Change Text with Click Events", "description": [ "When our click event happens, we can use Ajax to update an HTML element.", "Let's make it so that when a user clicks the \"Get Message\" button, we change the text of the element with the class message to say \"Here is the message\".", "We can do this by adding the following code within our click event:", "  $(\".message\").html(\"Here is the message\");" ], "tests": [ "assert(code.match(/\\$\\s*?\\(\\s*?(?:'|\")\\.message(?:'|\")\\s*?\\)\\s*?\\.html\\s*?\\(\\s*?(?:'|\")Here\\sis\\sthe\\smessage(?:'|\")\\s*?\\);/gi), 'message: Clicking the \"Get Message\" button should give the element with the class message the text \"Here is the message\".');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", " $(\"#getMessage\").on(\"click\", function(){", " // Only change code below this line.", " ", " // Only change code above this line.", " });", " });", "fcces", "", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Cambia texto con eventos de pulsación", "descriptionEs": [ "Cuando nuestro evento de pulsación ocurre, podemos utilizar Ajax para actualizar un elemento HTML.", "Hagamos que cuando un usuario pulse el botón \"Get Message\", el texto del elemento con la clase message cambie para decir \"Here is the message\".", "Podemos hacerlo añadiendo el siguiente código dentro de nuestro evento de pulsación:", "  $(\".message\").html(\"Here is the message\");" ] }, { "id": "bb000000000000000000002", "title": "Get JSON with the jQuery getJSON Method", "description": [ "You can also request data from an external source. This is where APIs come into play.", "Remember that APIs - or Application Programming Interfaces - are tools that computers use to communicate with one another.", "Most web APIs transfer data in a format called JSON. JSON stands for JavaScript Object Notation.", "You've already been using JSON whenever you create a JavaScript object. JSON is nothing more than object properties and their current values, sandwiched between a { and a }.", "These properties and their values are often referred to as \"key-value pairs\".", "Let's get the JSON from Free Code Camp's Cat Photo API.", "Here's the code you can put in your click event to do this:", "  $.getJSON(\"/json/cats.json\", function(json) {", "    $(\".message\").html(JSON.stringify(json));", "  });", "Once you've added this, click the \"Get Message\" button. Your Ajax function will replace the \"The message will go here\" text with the raw JSON output from the Free Code Camp Cat Photo API." ], "tests": [ "assert(code.match(/\\$\\s*?\\(\\s*?(\\\"|\\')\\#getMessage(\\\"|\\')\\s*?\\)\\s*?\\.\\s*?on\\s*?\\(\\s*?(\\\"|\\')click(\\\"|\\')\\s*?\\,\\s*?function\\s*?\\(\\s*?\\)\\s*?\\{/gi), 'message: You should have a click handler on the getMessage button to trigger the AJAX request.');", "assert(code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi), 'message: You should have at least one closing set of brackets and parenthesis.');", "assert(code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi) && code.match(/\\,\\s*?function\\s*?\\(\\s*?\\w*?\\s*?\\)\\s*?\\{/gi) && code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi).length === code.match(/\\s*?function\\s*?\\(\\s*?\\w*?\\s*?\\)\\s*?\\{/gi).length, 'message: Each callback function should have a closing set of brackets and parenthesis.');", "assert(code.match(/\\$\\s*?\\.\\s*?getJSON\\s*?\\(\\s*?(\\\"|\\')\\\/json\\\/cats\\.json(\\\"|\\')\\s*?\\,\\s*?function\\s*?\\(\\s*?json\\s*?\\)\\s*?\\{/gi), 'message: You should be making use of the getJSON method given in the description to load data from the json file.');", "assert(code.match(/\\$\\s*?\\(\\s*?(\\\"|\\')\\.message(\\\"|\\')\\s*?\\)\\s*?\\.\\s*?html\\s*?\\(\\s*?JSON\\s*?\\.\\s*?stringify\\s*?\\(\\s*?json\\s*?\\)\\s*?\\)/gi), 'message: Don't forget to make the .html change the contents of the message box so that it contains the result of the getJSON.');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", "", " $(\"#getMessage\").on(\"click\", function(){", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", " });", "", " });", "fcces", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Obtén JSON con el método getJSON de jQuery", "descriptionEs": [ "También puedes solicitar los datos de una fuente externa. Aquí es donde entran en juego las API. ", "Recuerda que las API - o interfaces de programación de aplicaciones - son herramientas que utilizan los ordenadores para comunicarse entre sí.", "La mayoría de las API para el web transfieren datos en un formato llamado JSON. JSON significa notación de objeto JavaScript (JavaScript Object Notation).", "Tú ya has usado JSON al crear objetos en JavaScript. JSON no es más que las propiedades del objeto y sus valores actuales, intercalados entre un { y un }. ", "Estas propiedades y sus valores a menudo se denominan \" pares llave-valor\".", "Vamos a obtener el JSON de la API de fotos de gato de Free Code Camp.", "Aquí está el código que puedes poner en tu evento de pulsación para lograrlo:", "  $.getJSON(\"/json/cats.json\", function(json) {", "    $(\".message\").html(JSON.stringify(json));", "  });", "Una vez lo añadas, pulsa el botón \"Get Message\". Su función Ajax sustituirá el texto \"The message will go here\" con la salida JSON en bruto de la API de fotos de gato de Free Code Camp." ] }, { "id": "bb000000000000000000003", "title": "Convert JSON Data to HTML", "description": [ "Now that we're getting data from a JSON API, let's display it in our HTML.", "We can use the .forEach() method to loop through our data and modify our HTML elements.", "First, let's declare an html variable with var html = \"\";.", "Then, let's loop through our JSON, adding more HTML to that variable. When the loop is finished, we'll render it.", "Here's the code that does this:", "json.forEach(function(val) {", "  var keys = Object.keys(val);", "  html += \"<div class = 'cat'>\";", "  keys.forEach(function(key) {", "    html += \"<b>\" + key + \"</b>: \" + val[key] + \"<br>\";", "  });", "  html += \"</div><br>\";", "});" ], "tests": [ "assert(code.match(/json\\.forEach/gi), 'message: The message box should have something in it.');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", "", " $(\"#getMessage\").on(\"click\", function() {", "   $.getJSON(\"/json/cats.json\", function(json) {", "", " var html = \"\";", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", "", "     $(\".message\").html(html);", "", "   });", " });", " });", "fcces", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Convierte datos JSON a datos HTML", "descriptionEs": [ "Ahora que estamos obteniendo datos de una API JSON, mostremóslos en nuestro HTML.", "Podemos usar el método .forEach() para recorrer nuestros datos y modificar nuestros elementos HTML.", "En primer lugar, vamos a declarar una variable llamada html con var html = \"\";.", "Después, iteremos a traveś de nuestro JSON, añadiendo más HTML a esa variable. Cuando se termina el ciclo, vamos a presentarla. ", "Aquí está el código que hace esto:", "json.forEach(function(val) {", "  var keys = Object.keys(val);", "  html += \"<div class = 'cat'>\";", "  keys.forEach(function(key) {", "    html += \"<b>\" + key + \"</b>: \" + val[key] + \"<br>\";", "  });", "  html += \"</div><br>\";", "});" ] }, { "id": "bb000000000000000000004", "title": "Render Images from Data Sources", "description": [ "We've seen from the last two lessons that each object in our JSON array contains an imageLink key with a value that is the url of a cat's image.", "When we're looping through these objects, let's use this imageLink property to display this image in an img element.", "Here's the code that does this:", "  html += \"<img src = '\" + val.imageLink + \"'>\";" ], "tests": [ "assert(code.match(/val.imageLink/gi), 'message: You should have used the imageLink property to display the images.');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", "", " $(\"#getMessage\").on(\"click\", function() {", "  $.getJSON(\"/json/cats.json\", function(json) {", "", " var html = \"\";", "", " json.forEach(function(val) {", "", " html += \"
\";", "", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", "", " html += \"
\";", "", " });", "", "     $(\".message\").html(html);", "", " });", " });", " });", "fcces", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Presenta imágenes de fuentes de datos", "descriptionEs": [ "Tanto en el JSON que recibimos de la API de fotos de gato de Free Code Camp, como en ", "lo que hemos visto en las dos últimas lecciones, cada objeto en nuestro vector JSON contiene una llave imageLink con un valor que corresponde a la url de la imagen de un gato.", "Cuando estamos recorriendo estos objetos, usemos esta propiedad imageLink para visualizar la imagen en un elemento img.", "Aquí está el código que hace esto:", "  html += \"<img src = '\" + val.imageLink + \"'>\";" ] }, { "id": "bb000000000000000000005", "title": "Prefilter JSON", "description": [ "If we don't want to render every cat photo we get from our Free Code Camp's Cat Photo JSON API, we can pre-filter the json before we loop through it.", "Let's filter out the cat whose \"id\" key has a value of 1.", "Here's the code to do this:", "json = json.filter(function(val) {", "  return(val.id !== 1);", "});" ], "tests": [ "assert(code.match(/filter/gi), 'message: You should be making use of the .filter method.');" ], "challengeSeed": [ "fccss", " $(document).ready(function() {", "", " $(\"#getMessage\").on(\"click\", function() {", "   $.getJSON(\"/json/cats.json\", function(json) {", "", " var html = \"\";", "", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", "", " json.forEach(function(val) {", "", " html += \"
\"", "", " html += \"\"", "", " html += \"
\"", "", " });", "", "     $(\".message\").html(html);", "", "   });", " });", " });", "fcces", "", "
", "
", "

Cat Photo Finder

", "
", "
", "
", " The message will go here", "
", "
", "
", "
", " ", "
", "
", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Pre-filtra JSON", "descriptionEs": [ "Si no queremos presentar cada foto de gato que obtengamos de la API JSON de fotos de gato de Free Code Camp, podemos pre-filtrar el json antes de iterar a través de este.", "Vamos a filtrar el gato cuya llave \"id\" tiene un valor de 1.", "Aquí está el código para hacer esto:", "json = json.filter(function(val) {", "  return(val.id !== 1);", "});" ] }, { "id": "bb000000000000000000006", "title": "Get Geo-location Data", "description": [ "Another cool thing we can do is access our user's current location. Every browser has a built in navigator that can give us this information.", "The navigator will get our user's current longitude and latitude.", "You will see a prompt to allow or block this site from knowing your current location. The challenge can be completed either way, as long as the code is correct.", "By selecting allow you will see the text on the output phone change to your latitude and longitude", "Here's some code that does this:", "if (navigator.geolocation) {", "  navigator.geolocation.getCurrentPosition(function(position) {", "    $(\"#data\").html(\"latitude: \" + position.coords.latitude + \"<br>longitude: \" + position.coords.longitude);", "  });", "}" ], "tests": [ "assert(code.match(/navigator\\.geolocation\\.getCurrentPosition/gi), 'message: You should make use of the navigator.geolocation to access the users current location.');" ], "challengeSeed": [ "fccss", " // Only change code below this line.", " ", " ", " ", " // Only change code above this line.", "fcces", "
", "

You are here:

", " ", "
" ], "challengeType": 0, "type": "waypoint", "nameEs": "Recibir datos de Geo-localización", "descriptionEs": [ "Otra cosa interesante que podemos hacer es acceder a la ubicación actual de nuestros usuarios. Todos los navegadores han incorporado un geo-localizador que nos puede dar esta información. ", "El navegador puede obtener la longitud y latitud actual de nuestros usuarios.", "Como usuario verás un mensaje para permitir o evitar que el sitio conozca tu ubicación actual. El desafío se puede completar de cualquier manera, siempre y cuando el código sea correcto. ", "Si lo permites, verás que el texto en el teléfono de la derecha cambiará con tu latitud y longitud", "Aquí hay un código que hace esto:", "if (navigator.geolocation) {", "  navigator.geolocation.getCurrentPosition(function(position) {", "    $(\"#data\").html(\"latitude: \" + position.coords.latitude + \"<br>longitude: \" + position.coords.longitude);", "  });", "}" ] } ] }