Chapter 11: AJAX

License Information

The following is a sample results list from a link resolver, showing several full-text options from different databases.

Article Journal Academic Search Database 1986-present
Article Journal ProSearching Search Database 1991-1999
Article Journal Tiny Specialist Database 1991-1999
Show Markup
<div id="linkresolver" class="sample">
    <table>
      <tr class="row">
        <td>
          <table>
            <tr>
              <td class="article"><a href="#article1">Article</a></td>
              <td class="journal"><a href="#journal1">Journal</a></td>
              <td class="database"><a href="#database1">Academic Search Database</a></td>
              <td class="dates">1986-present</td>
            </tr>
          </table>
        </td>
      </tr>
      <tr>
        <td>
          <table>
            <tr class="row">
              <td class="article"><a href="#article2">Article</a></td>
              <td class="journal"><a href="#journal2">Journal</a></td>
              <td class="database"><a href="#database2">ProSearching Search Database</a></td>
              <td class="dates">1991-1999</td>
            </tr>
          </table>
        </td>
      </tr>
      <tr>
        <td>
          <table>
            <tr class="row">
              <td class="article"><a href="#article3">Article</a></td>
              <td class="journal"><a href="#journal3">Journal</a></td>
              <td class="database"><a href="#database3">Tiny Specialist Database</a></td>
              <td class="dates">1991-1999</td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
   </div>

The code below will grab a remote JSON file and parse it, adding a link to license information after each of the database names.

// Get all the database names on the page, define global databaseList variable
var databaseNames = $(".database"), databaseList;

// Grab the JSON object from the text file
$.get('http://mreidsma.github.io/vendor_tools/resources/licenses.json', function(data) {
	var databaseList = data;
  console.log(data);

  // Find the databases in the databaseList, append links
  for(i = 0; i < databaseNames.length; i++) {
  // Get the database name from the page
  var databaseText = $(databaseNames[i]).find('a').text();
  console.log(databaseList[databaseText]);
  var licenseURL = databaseList[databaseText];
  $(databaseNames[i]).append('&nbsp;<a href="' + licenseURL + '" class="license">License Information</a>');
}
});

Here is the contents of the license data file, in JSON format:

{
"Academic Search Database": "http://path/to/license1",
"ProSearching Search Database": "http://path/to/license2",
"Tiny Specialist Database": "http://path/to/license3"
}

Show All OPAC Holdings

The table below is a sample results table from an OPAC, truncated at 10 holdings. There is a link at the bottom that allows you to view all holdings for this item on a a separate page.

Location Call No. Status
FREY Circulating Collection (CHS 290) PS3568.A572 A6 2014 c.21 ON HOLDSHELF
FREY Circulating Collection (CHS 290) PS3568.A572 A6 2014 c.22 DUE 11-30-15
FREY Circulating Collection (CHS 290) PS3568.A572 A6 2014 c.23  AVAILABLE
 FREY Circulating Collection (CHS 290)  PS3568.A572 A6 2014  c.24    AVAILABLE
 FREY Circulating Collection (CHS 290)  PS3568.A572 A6 2014  c.25    AVAILABLE
 Mary Idema Pew - 4th Floor  PS3568.A572 A6 2014    DUE 11-02-15 +1 RECALLED
 Mary Idema Pew - 4th Floor  PS3568.A572 A6 2014  c.2 c.2  DUE 11-19-15
 Mary Idema Pew - Course Reserves  Community Reading Project - Citizen: An American Lyric  c.26    AVAILABLE
 Mary Idema Pew - Course Reserves  Community Reading Project - Citizen: An American Lyric  c.27    AVAILABLE
 Mary Idema Pew - Course Reserves  Community Reading Project - Citizen: An American Lyric  c.28    AVAILABLE

View All Holdings

The following code uses the jQuery .load() method to pull the entire list of holdings from an external URL, then parses that data to make a listing of all holdings on this page by availability, formatted in the same manner as our earlier scripts to reformat the OPAC results. Try it out in the console!

// Reformat new items into arrays
  var allHoldings = new Array(), availableHoldings = new Array(), unavailableHoldings = new Array(), periodicals;
  
  console.log('There are more than 10 holdings for this item.');

  // Get URL of additional copies
  var loadUrl = 'resources/allholdings.html';

  // Load additional copies into hidden div for processing
  var hiddenDiv = document.createElement('div');
  hiddenDiv.id = 'additionalCopies';
  hiddenDiv.style.display = 'none';
  document.body.appendChild(hiddenDiv);

  $('#additionalCopies').load(loadUrl + ' .bib_items', function() {

    console.log('The element has loaded');

    // Hide the view additional button
    $('#allholdings-link').hide();

    $(this).find('tr.bibItemsEntry').each(function() {

        var availText = $(this).find('td:last-child').text().trim();
        var aLocation = $(this).find('td:first').text().trim();
        var aCallNo = $(this).find('td:nth-child(2)').text().trim();

          if(availText.indexOf('AVAILABLE') > -1) {
            // Add to available object
            availableHoldings.push({"Availability": availText, "Classes": "availability avail", "Location": aLocation, "Callno": aCallNo});
          } else {
            // Add to unavailable object
            unavailableHoldings.push({"Availability": availText, "Classes": "availability unavail", "Location": aLocation, "Callno": aCallNo});
          }

      });

      // Combine all items
      allHoldings = availableHoldings.concat(unavailableHoldings);

      // Now start inserting the additional items under the first ten
      // Keep this DIV hidden, and also include a trigger to show additional items
      $('.bib_items').find('tbody').hide();
      $('.bib_items').append('<div id="top-results"></div>');
      $('.bib_items').append('<div id="trigger">Show Additional Copies</div>');
      $('.bib_items').append('<div id="additional-results" style="display:none;"></div>');

      $('#trigger').css('color', '#1F65A0').css('cursor','pointer').css('margin-top','1em');

      $('#trigger').click(function() {
        $('#additional-results').slideToggle(400);
        if($(this).text() == 'Show Additional Copies') {
          $(this).text('Hide Additional Copies');
        } else {
          $(this).text('Show Additional Copies');
        }
      });

      for(t=0;t < allHoldings.length; t++) {

        if(t < 10) {
          $('#top-results').append('<div class="availability-table"><span class="' + allHoldings[t].Classes + '">' + allHoldings[t].Availability + '</span> <span class="location">' + allHoldings[t].Location + '</span> <span class ="call-number">' + allHoldings[t].Callno + '</span></div>');
        } else {
          $('#additional-results').append('<div class="availability-table"><span class="' + allHoldings[t].Classes + '">' + allHoldings[t].Availability + '</span> <span class="location">' + allHoldings[t].Location + '</span> <span class ="call-number">' + allHoldings[t].Callno + '</span></div>');
        }
      }

  });

Getting Data out of Vendor Tools

The following code saves a predefined ISBN number (in the variable isbn) to a text file on a remote server. We'll look at the PHP code in Chapter 13.

var isbn = '1582348251';
$.ajax({
  method: "POST",
  crossdomain: true,
  url: "http://matthew.reidsrow.com/courseware/vendortools/week4/ajax1.php",
    data: {no: isbn}
}).done(function(msg) {
  alert( "Data Saved: " + msg );
});

To see the file that records the ISBN number, visit http://gvsu.edu/s/00Y.

Here is another script that uses the JavaScript prompt method to ask for user input, and then saves the answer in a remote text file.

var movie = prompt("What is your favorite movie?");

$.ajax({
    method: "POST",
    crossdomain: true,
    url: "http://matthew.reidsrow.com/courseware/vendortools/week4/ajax2.php",
    data: {film: movie}
}).done(function(msg) {
    alert( "All set! I loved " + movie + " too." );
});

You can see the text file that saves the answers at http://gvsu.edu/s/00Z.

Here's one more, using a technique different from AJAX. This one just inserts an <img> tag on the site that does an HTTP request to a script on a remote server.

var path = encodeURIComponent(window.location.href);
var title = encodeURIComponent(document.title);
var imageHack = document.createElement('img');
imageHack.style.display = 'none';
imageHack.src = 'http://matthew.reidsrow.com/tools/bookmarks.php?url=' + path + '&title=' + title;
document.body.appendChild(imageHack);
alert('Your URL was saved.');

You can see the file that records the data at http://gvsu.edu/s/010. We'll look at the techniques needed to save the data to the server in Chapter 13.