title: jQuery & AJAX: preventDefault on link, run AJAX request, then follow that link
body: <p>I have this presumably 'simple' task that is absolutely kicking my butt.</p>
  
  <p>My aim is that when a user clicks a link, I prevent the default, run an ajax function on it, then follow that link (ie. resume default). The only thing I can get to work is capturing the href of the link and then following using window.location - this is not ideal, as it doesn't detect whether a user has opted to open in a new window/tab or in the same window/tab; also I think there must be a better way.</p>
  
  <p>However what is happening is that the default is prevented, AJAX function is run but the link is not then followed. What I'm asking is: how to simulated the link click <em>after</em> the function has run?</p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;a href="some_href" data-id="789"&gt;This is the link&lt;/a&gt;
  </code></pre>
  
  <p><strong>jQuery</strong></p>
  
  <pre><code>$(document).on('click', 'a', function(e, options){
  
    // setup our options
    options = options || {};
  
    // get some details from the link
    var this_href = $(this).attr('href');
    var this_id = $(this).data('id');
  
    // if options aren't set and this link has a data-id attribute
    if(!options.stuff_done &amp;&amp; $(this_id).length){
  
      e.preventDefault(); // prevent link following
  
      // run some ajax
      $.ajax({
        url: myAjax.ajax_url,
        type: 'post',
        data: {
          action : 'a_php_function',
          post_id : this_id
        },
        success: function(response) {
          // do stuff
        }).then(function(){
          $(this).trigger('click', { stuff_done: true });
        });
  
    } else {
      // else if it doesn't have a data-id, do default
    }
  });
  </code></pre>
  
  <p><em>Context:</em> Checking if a value ('data-id') is in an array using PHP/AJAX and if it is, removing it. This data-id relates to a post's ID in Wordpress, and needs to be removed when a user follows a link to that post. </p>
  
  <p>Hence - user clicks link, data-id is checked, removed/not-removed from array, link is followed.</p>