Home > Enterprise >  Visit a page using Javascript without leaving the current page
Visit a page using Javascript without leaving the current page

Time:10-31

I have a Javascript file running on a page and I would like to log certain events as they occur. For example, I have a web store - and when people add an item to their cart, I want to log this event by visiting a page that I built:

function log_event(id) {
  window.location.href = 'https://example.com/log/cart.php?id='   id;
  return false;
}

The log/cart.php page doesn't really have anything to display, all it does is insert a record into a database containing the item that was added to the cart, and the date.

The code that calls this function looks like:

document.getElementById('add-to-cart').addEventListener('click', function() {
  // Add to the cart
  ...

  // Track the item that was added
  let id = document.getElementById('add-to-cart').getAttribute('data-id');
  log_event(id);
});

With my current code, the log/cart.php actually replaces the current page. I want the opening of log/cart.php to only happen in the background without the user being interrupted. I don't want it to actually open a browser tab or window and let the user stay in the product page.

CodePudding user response:

You can send an AJAX request to that endpoint:

function log_event(id) {
  var xhttp = new XMLHttpRequest();
  xhttp.open("GET", 'https://example.com/log/cart.php?id='   id, true);
  xhttp.send();
  return false;
}

fetch() can also be used, but be aware of its browser support (no IE).

  • Related