Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Practice exercises CHAPTER 8 389



  1. In the ContactUs.js file, add a callServer function that uses jQuery to make an AJAX
    call that posts the data to the /ContactService URL and puts the result into the <div
    id=”result”> element.
    Your code should look like the following.
    function callServer() {
    var data = $('#ContactForm').serialize();
    $.post('/ContactService', data, function (returnObject) {
    $('#result').html(returnObject.result);
    },'json');
    }

  2. In the ContactUs.js file, add a reference to jQuery and add a $(document).ready() func-
    tion with a call to subscribe to the click event of the submit button so that clicking the
    submit button executes the callServer function.
    The completed ContactUs.js file should look like the following.
    ///


$(document).ready(function () {
$('#submit').on('click', callServer);
});

function callServer() {
var data = $('form[name="ContactForm"]').serialize();
$.post('/ContactService', data, function (returnObject) {
$('#result').html(returnObject.result);
}, 'json');
}


  1. Stop and start ContosoWeb.

  2. In the browser, navigate to the ContactUs.html page.

  3. Press Ctrl+F5 to ensure that you have the latest version of the file.

  4. Enter data in the form and click the Submit button.
    Instead of seeing a new page, you should see the result on the same page, as shown in
    Figure 8-15.

Free download pdf