4
\$\begingroup\$

I have a script which dynamically loads data onto a restaurant menu for printing. Could the following code could be shortened at all?

    <script>
                $(document).ready(function(){
                $('#prestarters').load('prestarters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                $('#starters').load('starters.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });

                        $('#mains').load('mains.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });


                        $('#sides').load('sides.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }
            });             
                $('#dessert').load('dessert.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#dessertwines').load('dessertwines.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#afterdinnerdrinks').load('afterdinnerdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#whiskeys').load('whiskeys.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#hotdrinks').load('hotdrinks.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#ports').load('ports.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#cognacs').load('cognacs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
                            $('#liqueurs').load('liqueurs.php', '', function(response, status, xhr) {
                if (status == 'error') {
                var msg = "Sorry but there was an error: ";
            $(".s").html(msg + xhr.status + " " + xhr.statusText);
            }

        });
    });
    </script>  

Also, is there a way to alert the user once all data has been loaded? I currently have a message which tells the user to wait 5 - 10 seconds before printing...

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Piece iterates over list, calling same $.ajax(), err or, other functions, etc., for each item within list. Save list items to _list , poll until _list.length === list.length - all list items processed - display "menu ready" to viewer.

JSFiddle

(function menus() {

var list = ["prestarters"
           , "starters"
           , "mains"
           , "sides"
           , "dessert"
           , "dessertwines"
           , "afterdinnerdrinks"
           , "whiskeys"
           , "hotdrinks"
           , "ports"
           , "cognacs"
           , "liqueurs"];

var err = function (jqxhr, textStatus, errorThrown) {
    if (textStatus == 'error') {
        var msg = "Sorry but there was an error: ";
        $(".s")
            .html(msg + textStatus + " " + errorThrown);
    };
};

var _list = [];

$.each(list, function (index, value) {
    $.when(value)
        .then(function (data) {
        // var _ids = "#" + data;
        // var _urls = data + ".php";
        // console.log(_ids, _urls);
        // i.e.g.,
        // `$.get(data + ".php")`
        $.post("/echo/json/", {
            json: JSON.stringify([value])
        }, "json")
            .then(function (response, textStatus, jqxhr) {
            _list.push(response);
            // `html`
            $("<section>", {
                    "id": response[0],
                    "html": response[0] + "<br />"
            }).appendTo("#menu");
        }, err)
            .always(function (response, textStatus, jsxhr) {
                // `always` complete callback,
                // when `list` complete
            if (_list.length === list.length) {
                $("<data>" + _list.length + " menus ready</data>")
                    .css({
                    "position": "absolute",
                    "left": "200px",
                    "top": "32px",
                    "fontSize": "28px",
                    "color": "blue"
                })
                .prependTo("#menu") && $("data").fadeOut(7500, function () {
                    $("#menu data").remove()
                });
                // alert(_list.length + " menus ready")
            };
        })
    })
});
}());
\$\endgroup\$
2
  • \$\begingroup\$ Any more info on this? I tried to simply copy and paste but did not work, I will not pretend to be a js expert so a little guidance would be greatly appreciated! \$\endgroup\$ Jul 6, 2014 at 20:56
  • \$\begingroup\$ Note, url of jsfiddle is /echo/json/ . Also, expected return dataType of piece is json. Try change url to $.post(data + ".php") . Also, change "id":response[0] to "id":data , if dynamically creating menu containers - as at piece. See jsfiddle html, where a container with id of #menu was utilized for each menu item. .load() method at OP did not specify returned html ? Is data returned from php calls ? Thanks \$\endgroup\$ Jul 6, 2014 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.