Click here to Skip to main content
13,146,742 members (79,950 online)
Click here to Skip to main content
Add your own
alternative version

Stats

8.8K views
7 bookmarked
Posted 13 May 2016

How to Insert Data into a Placeholder on a Web Page (Poor Man's SPA)

, 13 May 2016
Rate this:
Please Sign up or sign in to vote.
Using HTML and jQuery/AJAX to dynamically modify the contents of a Web page

Reasons To Move Your Page's Cheese

If you want to avoid:

  • jQuery's Alert() because it's "plain jane" and not very programmable
  • jQuery UI's dialog because of the overhead and hassle of using it
  • directing the user to another page because you want to keep your design simple and the user on the same page (literally)

...a "poor man's SPA" design might interest you.

Here's how I did it, when I wanted the results of an AJAX call to display on the same page as the button that invoked the process, and then programmatically move down the page to display those results:

Add an Empty Container

At the place where you want the data to go, add a placeholder like so:

<div id="tableshell"></div>

In my case, I added that to the very end of the HTML (the bottom of the page); I add a dynamically created HTML table, that's why it's named "tableshell".

Snatch and Plop the Data

Now all you need to do is get the data (the setting up of the Controller side of the AJAX call is left as an exercise for you, o wise and googlemeisterly reader, although the code of the method itself is shown below) via an AJAX call and assign it to that div:

$("#btnViewList").click(function () {
    $("#lblrptgenprogress").removeClass("invisible");
    document.body.style.cursor = 'wait';
    $.ajax({
        type: "GET",
        url: '@Url.Action("GenerateReportFutures", "GenerateScheduledRpts")',
        success: function (retval) {
            $("#tableshell").append($(retval));
            document.getElementById("tableshell").scrollIntoView();
            $("#lblrptgenprogress").addClass("invisible");
            document.body.style.cursor = 'pointer';
        },
        error: function () {
            alert('error in btnViewList');
        }
    });
}); 

As you can see, when a button (with the ID "btnViewList") is clicked, I:

  • Show an explanatory label (by removing the label's "invisible" class)
  • Show an "hourglass" (by setting the cursor to 'wait')
  • Make the AJAX call to get the data (the first arg passed to Url.Action() is the name of the method; the second arg is the controller name sans the "Controller" appendage)
  • In the AJAX call's "success" function, append the returned data to the "placeholder" div
  • Scroll the page so that the new data is at the top of the page (user has to scroll/page up to return to where they were before)
  • Make the "progress" label invisible again by adding back the "invisible" class
  • Remove the "hourglass" cursor by setting the cursor back to the default "pointer"

Dirt Banned

Now for the nitty gritty, here's the rest of the related HTML:

<div class="col-md-7">
    <button class="btn pseudobtn darkgreentext marginaboveandbelow" id="btnViewList">
    View List of Future Report Generation</button>
    <label id="lblrptgenprogress" class="invisible redfont">
    Report generation list is being constructed...</label>
</div>

...and CSS:

.invisible {
    visibility: hidden;
}

.redfont {
    color: red;
}

...and (last but not least) C# (Server side/Controller method called by jQuery AJAX):

public class GenerateScheduledRptsController : Controller
{
    private static List<queuedreports> futureReports;

    public string GenerateReportFutures()
    {
        StringBuilder sb = new StringBuilder();
        futureReports = GetAllFutureReports();
        try
        {
            sb.Append("<div class=\"row\">");
            sb.Append("<div class=\"col-md-12\">");
            sb.Append("<hr />");
            sb.Append("</div>");
            sb.Append("</div>");

            sb.Append("<h2 class=\"titletext\" style=\"width: 50%;
                      margin: 0px auto;\">REPORTS TO BE GENERATED</h2>");
            sb.Append("<br />");
            sb.Append("<table class=\"centeredmargined\" border=\"1\" >");
            sb.Append("<tr>");
            sb.Append("<th nowrap>Report Name</th>");
            sb.Append("<th nowrap>Unit</th>");
            sb.Append("<th nowrap>Generation Date</th>");
            sb.Append("<th nowrap>Data Begin Date</th>");
            sb.Append("<th nowrap>Data End Date</th>");
            sb.Append("<th>Recipients</th>");
            sb.Append("</tr>");

            foreach (QueuedReports qr in futureReports)
            {
                if (qr.NextExecution > DateTime.Now.AddMonths(3))
                {
                    continue;
                }
                sb.Append("<tr>");
                sb.Append(string.Format("<td nowrap>{0}</td>", qr.ReportName));
                sb.Append(string.Format("<td nowrap>{0}</td>", qr.Unit));
                sb.Append(string.Format("<td nowrap>{0}</td>", qr.NextExecution.ToLongDateString()));
                sb.Append(string.Format("<td nowrap>{0}</td>",
                          qr.NextExecutionsBeginDateArg.ToLongDateString()));
                sb.Append(string.Format("<td nowrap>{0}</td>",
                          qr.NextExecutionsEndDateArg.ToLongDateString()));
                sb.Append(string.Format("<td>{0}</td>", qr.AllEmailAddresses));
                sb.Append("</tr>");
            } // foreach
            sb.Append("</table>");
            return sb.ToString();
        } // try
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return sb.ToString();
    } // GenerateOfReportFutures

Knock Yourself Out/Go Wild

Of course, you don't have to append your dynamically generated HTML exclusively to the end of a page; you can put it after any element where it makes sense to do so, such as after a button when you want to show some message or feedback to the user relevant to their clicking the button, or...wherever you want.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

B. Clay Shannon
Founder Across Time & Space
United States United States
I am in the process of morphing from a software developer into a portrayer of Mark Twain. My monologue (or one-man play, entitled "The Adventures of Mark Twain: As Told By Himself" and set in 1896) features Twain giving an overview of his life up till then. The performance includes the relating of interesting experiences and humorous anecdotes from Twain's boyhood and youth, his time as a riverboat pilot, his wild and woolly adventures in the Territory of Nevada and California, and experiences as a writer and world traveler, including recollections of meetings with many of the famous and powerful of the 19th century - royalty, business magnates, fellow authors, as well as intimate glimpses into his home life (his parents, siblings, wife, and children).

Peripatetic and picaresque, I have lived in eight states; specifically, besides my native California (where I was born and where I now again reside) in chronological order: New York, Montana, Alaska, Oklahoma, Wisconsin, Idaho, and Missouri.

I am also a writer of both fiction (for which I use a nom de plume, "Blackbird Crow Raven", as a nod to my Native American heritage - I am "½ Cowboy, ½ Indian") and nonfiction, including a two-volume social and cultural history of the U.S. which covers important events from 1620-2006: http://www.lulu.com/spotlight/blackbirdcraven

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralMy vote of 4 Pin
eslipak18-May-16 9:41
professionaleslipak18-May-16 9:41 
QuestionGood tip Pin
harrybowles17-May-16 0:53
memberharrybowles17-May-16 0:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170915.1 | Last Updated 13 May 2016
Article Copyright 2016 by B. Clay Shannon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid