jQuery Ajax

Write jQuery code to load JSON data with Ajax and show it in a list

Description: The file courses.json has a list of courses. Load it and show the titles in the list.

Hint:

  • Use $.getJSON() and $.each().

The JSON file and the HTML

[
  { "id": 1, "title": "HTML Basics" },
  { "id": 2, "title": "CSS Layouts" },
  { "id": 3, "title": "jQuery Tutorial" }
]
<ul id="courses"></ul>

Solution

$.getJSON('courses.json')
  .done(function (courses) {
    $.each(courses, function (i, course) {
      $('<li>').text(course.title).appendTo('#courses');
    });
  })
  .fail(function () {
    $('#courses').text('Could not load the courses');
  });
HTML after the code runs

<ul id="courses">
<li>HTML Basics</li>
<li>CSS Layouts</li>
<li>jQuery Tutorial</li>
</ul>

How it works

  • $.getJSON() loads the file and parses it into an array.
  • We create a list item with .text() for each course.
  • The fail() handler shows a message if the file cannot be loaded.

Read jQuery Ajax.

Write jQuery code to submit a form with Ajax

Description: Submit the contact form in the background, and show the message from the server below the form.

Hint:

  • Use e.preventDefault(), .serialize() and $.ajax().

HTML of the page

<form id="contact" action="send" method="post">
  <input type="text" name="name" value="Anita">
  <input type="email" name="email" value="anita@example.com">
  <button type="submit">Send</button>
</form>
<p id="result"></p>

Solution

$('#contact').on('submit', function (e) {
  e.preventDefault();

  $.ajax({
    url: $(this).attr('action'),
    method: $(this).attr('method'),
    data: $(this).serialize(),
    dataType: 'json'
  }).done(function (res) {
    $('#result').text('Server received: ' + res.received);
  }).fail(function () {
    $('#result').text('Sorry, there was an error.');
  });
});

$('#contact').trigger('submit');
HTML after the code runs

<p id="result">Server received: name=Anita&email=anita%40example.com</p>

How it works

  • The data is sent as name=Anita&email=anita%40example.com. Here the test server only repeats it.
  • The page is not reloaded, and the result is shown in the paragraph.

Read jQuery Forms and jQuery Ajax.