Skip to main content

Errors Returned from AJAX Portal POST Methods

When you fire a custom SQL POST method and the SQL crashes, the error message is displayed on-screen with branding for the user to read. That's great, but what if you call your method in the background with $.ajax() or similar? You might have careful state checking in your SQL that throws a beautiful error, and then it's just...gone.

Here's an example of a function that will listen for the returned message, extract the error, and do something with it. In this example, that something is alert(), but you could also log it to the console or do something else useful.

function handleAjaxError(data, defaultMessage) {
  console.log(data);
  
  // Extract error message from HTML response
  try {
    const parser = new DOMParser();
    const doc = parser.parseFromString(data.responseText, 'text/html');
    const errorElement = doc.querySelector('.error');
    if (errorElement) {
      alert(errorElement.textContent.trim());
    } else {
      alert(defaultMessage);
    }
  } catch (e) {
    alert(defaultMessage);
  }
  }

Here's an example of how that error function might be used. Notice that we have a default error message in case handleAjaxError can't extract the message for some reason.

function updateNote(noteId, claimedBy, followUpComments, closedDate) {
  const formData = {
    cmd: "note_update",
    e_id: noteId,
    claimed_by: claimedBy,
    follow_up_comments: followUpComments,
    closed_date: closedDate
  };

  FW.Progress.Load();

  $.ajax({
    url: '?cmd=note_update',
    method: 'POST',
    data: formData,
    success: function(data) {
      FW.Progress.Unload();
    },
    error: function(data) {
      handleAjaxError(data, 'An error occurred while updating the note. Please try again.');
      FW.Progress.Unload();
    }
  });
}