Using a Browser-side Event to Fire a POST Request

Sometimes, you might need browser-side events and backend-events to talk to each other. Unlike a friendly round-table discussion between the Montagues and the Capulets, it can be simpler than you think.

We have a couple of ways you can do that using JavaScript or jQuery. As a reminder, add this code to your Drift snippet- it should not replace what you got from the install page.

window.drift.on('emailCapture', function(e) {
  $.ajax({
    url: 'https://api.yoursite.com/form/endpoint/here',
    type: 'POST',
    data: {
      email: e.data.email,
      id: getCookie('userID'),
      utm_campaign: getUrlVars()["utm_campaign"]
      // Anything else you want to pass in
    }
  });
});

Above, we use Ajax to make the POST we need as soon as an email is captured in chat. Perhaps you need to make a time-sensitive update as soon as a certain piece of data is collected. You can do this with just about any combination of front and back end events that you like.

In the next example, we use plain JavaScript to do the same thing via event listeners.

window.drift.on('emailCapture', function(e) {
  const email = e.data.email;
  // Define other variables here
  let XHR = new XMLHttpRequest();
  XHR.addEventListener('load', function(event) {
    console.log('Success');
  });
  XHR.addEventListener('error', function(event) {
    console.log('Failed');
  });
  XHR.open('POST', 'https://api.yoursite.com/form/endpoint/here'); // Change to your POST endpoint
  XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  XHR.send(encodeURI('email='+email)); // Append additional fields here
});

Did this page help you?