Browser-side AJAX with jQuery

These examples illustrate some simple AJAX-based Web sites using jQuery. They are built to interact with particular servers built in Node.js, found here. (These are meant to supercede an earlier version of this page, found here.)

1. HTML-based communication

HTML page

<!DOCTYPE html>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Forum Example</title>
 </head>

 <body>
  <h1>Forum Example</h1>

  <div id="oldposts"></div>

  <h2>Post a New Message</h2>

  <form action="addnew" method="post">
   Name: <input name="name"></input><br>
   <textarea name="message"></textarea><br>
   <button type="submit">Post Message</button>
  </form>

  <script src="jquery-1.10.2.js"></script>
  <script src="forum-client.js"></script>
 </body>
</html>

Browser JavaScript

$(document).ready(function () {
    "use strict";
    $.ajax({ url'fetch'type'get'cachefalse,
        errorfunction (jqxhrtextStatuserrorThrown) {
            $('#oldposts').text('HTTP error: ' + textStatus);
        },
        successfunction (html) {
            $('#oldposts').html(html);
        }
    });
});

2. JSON-based communication

HTML page

The only part that changes from previous HTML is the <form> element.

<form id="addnew">
 Name: <input id="name"></input><br>
 <textarea id="message"></textarea><br>
 <button type="submit">Post Message</button>
</form>

Browser JavaScript

$(document).ready(function () {
    "use strict";

    function showPosts(jsonData) {
        var oldposts = $('#oldposts');
        oldposts.empty();
        if (jsonData.ok) {
            $.each(jsonData.postsfunction (indexpost) {
                var newElt = $('<div>');
                // SECURITY HOLE: Don't post raw HTML from user!
                newElt.html('<b>User:</b> ' + post.name + '<br />\n'
                    + '<div>' + post.message + '</div>');
                oldposts.append(newElt);
            });
        } else {
            oldposts.text(jsonData.message);
        }
    }

    $.ajax({ url'fetch'type'get'cachefalse,
        errorfunction (jqxhrtextStatuserrorThrown) {
            $('#oldposts').text('HTTP error: ' + textStatus);
        },
        successshowPosts
    });

    $('#addnew').submit(function (evnt) {
        evnt.preventDefault();
        $.ajax({ url'addnew'type'post'dataType'json',
            data: { name$('#name').val(), message$('#message').val() },
            errorfunction (jqxhrtextStatuserrorThrown) {
                $('#oldposts').text('HTTP error: ' + textStatus);
            },
            successshowPosts
        });
    });
});