Skip to content

Instantly share code, notes, and snippets.

@annajmorton
Created June 17, 2016 21:13
Show Gist options
  • Save annajmorton/3ccb8ff0888c8694c8c13216067b52aa to your computer and use it in GitHub Desktop.
Save annajmorton/3ccb8ff0888c8694c8c13216067b52aa to your computer and use it in GitHub Desktop.
Exercise Solutions - Ajax Intro

Ajax Request

Ajax Store

  1. Download and save ajax-store.html to your codeup.dev public directory.
  2. Create a data directory under public and download inventory.json to that folder.
  3. Your online tool store should load data from the JSON file using a get request and append the data to the table. You will need to use either $.ajax() or $.get(), and a .done() callback.
  4. Add some new entries to inventory.json and see how the data on the page gets updated.
  5. Add a "Refresh" button that will load inventory.json for you without having to refresh the entire page.
  6. Add Twitter Bootstrap to your online store with some custom CSS to make the style your own.
    [
        {
            "title": "Hammer",
            "quantity": 25,
            "categories": [
                "tool"
            ],
            "price": 20
        }, {
            "title": "Drill",
            "quantity": 5,
            "categories": [
                "tool",
                "powered"
            ],
            "price": 100
        }, {
            "title": "Mower",
            "quantity": 5,
            "categories": [
                "tool",
                "gas",
                "outdoor"
            ],
            "price": 200
        }, {
            "title": "Screwdrivers",
            "quantity": 25,
            "categories": [
                "tool"
            ],
            "price": 10
        }
    ]    
<!DOCTYPE html>
<html>
<head>
    <title>Online Store</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
    <h1>My Tool Store</h1>

    <table class="table table-striped" id="products">
        <thead>
            <tr>
                <th>Title</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Categories</th>
            </tr>
        </thead>
        <tbody id="insertProducts"></tbody>
    </table>
    <button id="ha" class="btn btn-default" type="button">refresh</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<script>
(function() {
    "use strict";
    function funAjax() {
        $.ajax(
            {
                url: '/data/inventory.json',
                type: "GET"
            }
        ).done(function(response){
            $('#insertProducts').html("");
            response.forEach(function(tool){
                var categories = tool.categories.join(' ');
                var row = `<tr>
                    <td>${tool.title}</td>
                    <td>${tool.quantity}</td>
                    <td>${tool.price}</td>
                    <td>${categories}</td>
                </tr>`;
                $('#insertProducts').append(row);

            })

        }).fail(function(){
            alert('the request didn\'t go through!');
        });
    };

    funAjax();    
    $('#ha').on('click', funAjax);

})();
</script>

</body>

Ajax Blog

  1. Create a new html file under codeup.dev/public called "ajax_blog.html".
  2. At minimum, your ajax blog will need an empty <div> with id="posts".
  3. Add your own Bootstrap theme to this file as well. Feel free to use the same one as your store or choose a different one.
  4. Download blog.json to your data directory from before.
  5. Use ajax to load the contents of blog.json and add the data from it to your #posts div.
  6. Add additional entries to blog.json and make sure your changes are reflected on the page.
[
    {
        "title": "My First Blog Post",
        "content": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        "categories": [
            "greek"
        ],
        "date": "January 25, 2015"
    }, {
        "title": "The Second Post",
        "content": "Cupcake ipsum dolor sit amet gummies. Cake chocolate sweet ice cream oat cake biscuit bear claw dessert. Jujubes marzipan toffee apple pie pastry dragée jujubes marshmallow. Dragée chocolate gingerbread liquorice chocolate bar jujubes. Sweet chocolate bar jelly-o chocolate cake candy carrot cake cotton candy macaroon marzipan. Sweet roll biscuit sweet gummies topping sesame snaps tootsie roll sugar plum pie. Sweet muffin croissant chocolate cake chupa chups. Donut croissant gummies donut powder ice cream. Chupa chups halvah apple pie topping jelly beans donut candy canes donut. Bonbon cake gummi bears cheesecake tart topping powder liquorice gummi bears.",
        "categories": [
            "family",
            "candy",
            "sweets",
            "sugar"
        ],
        "date": "February 14, 2015"
    }, {
        "title": "The Third Post",
        "content": "i can't deal with life!",
        "categories": [
            "no way",
            "no how"
        ],
        "date": "Today"
    }
]
<!DOCTYPE html>

<html>

    <head>
    
        <title>blOOOOOO - G!</title>
        
        <meta charset="utf8">

        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
        <style type="text/css">
                body{
                    background-color: #999966;
                    color: papayawhip;
                }
                .bs-calltoaction{
                    position: relative;
                    width:auto;
                    padding: 15px 25px;
                    border: 1px solid #ff8000;
                    margin-top: 10px;
                    margin-bottom: 10px;
                    border-radius: 5px;
                }

        </style>

    </head>

    <body>

        <div class="container-fluid">
            <h1>so fresh and so blooog</h1>
            <div id="posts"></div>
            <button id="refresh"class="btn btn-warning" type="button">load the latest</button>
        </div>

        <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script type="text/javascript">
            (function() {
                "use strict";
               function ajaxBlog() {
                    $.ajax(
                        {
                            url: '/data/blog.json',
                            type: "GET"
                        }
                    ).done(function(response){

                        console.log(response);
                        $('#posts').html("");
                        response.forEach(function(post){
                            var categories = post.categories.join(' ');
                            var row = `<div class="bs-calltoaction">
                                <h2>${post.title}</h2>
                                <p>${post.content}</p>
                                <div><h3>${post.date} ${categories}<h3></div>
                            </div>`;
                            $('#posts').append(row);

                        })

                    }).fail(function(){
                        alert('the request didn\'t go through!');
                    });
                };
                ajaxBlog();
                $('#refresh').on("click", ajaxBlog);
                console.log($('#refresh'));


            })();
        </script>

    </body>

</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment