Button Click triggers AJAX post and then continues

Button AJAX post and then continue with button action. Button gets clicked which then makes AJAX post to save a conversion on A/B testing DB. After saving a conversion, the button re-triggers a click but does not record a conversion so that the buttons original action runs.

by Jason Davis

HTML

<script src="https://cdn.rawgit.com/adamschwartz/log/master/log.min.js"></script>
<a class="cta-link-1" href="https://www.apollowebstudio.com">Click me to make an AJAX POST and save a conversion for this page and after that will continue on as a normal link click!</a>


<div id="info"></div>


<br><br><hr>
<small>HTTP POST made to <a href="https://posttestserver.com/post.php?dir=jason">https://posttestserver.com/post.php?dir=jason</a>. URL to view post results fwill show up in AJAX success.</small>

JavaScript

// version 1 for click event on class or ID
$('.cta-link-1').on('click', function (e, options)
{
  options = options || {};

  /* if options.record_ab_test_conversion_done flag not yet set to true, make AJAX post to record a conversion */
  if(!options.record_ab_test_conversion_done)
  {
    e.preventDefault();
    console.log('%c [1-Link Clicked] - Make AJAX post to save conversion', 'background: #222; color: #bada55');
 
    var pageData = {
        pageId: '123456789',
        abTestVariation: '2'
    }; 
    $.ajax({
        url : 'https://posttestserver.com/post.php?dir=jason',
        type: 'POST',
        data : pageData,
        //dataType : 'json',
        success: function(data, textStatus, jqXHR)
        {
            //data - response from server
            console.log(data);
            
            var $title = $('<h1>').text('Click AJAX result');
            var html = urlify(data);
            var $description = $('<p>').html('View browser console for more info<br>'+html);
            $('#info').append($title).append($description);

            // retrigger the click event with record_ab_test_conversion_done set to true so that this code will  
            // run again but next time will bypass the AJAX conversion saving part
            $(e.currentTarget).trigger('click', {
              'record_ab_test_conversion_done': true
            });
        },
        error: function (jqXHR, textStatus, errorThrown)
        {

        }
    }); 

  /* if options.record_ab_test_conversion_done flag is set to true, carry on with with default action */
  }else{
    /* allow default behavior to happen */
    console.log('%c [2-Link Clicked] - Triggered from AJAX success so this click should not record a conversion and should instead open the link as normal!', 'background: #222; color: #bada55');
    return true;
  }
});








function urlify(text) {
    var urlRegex = /(https?:\/\/[^\s]+)/g;
    return text.replace(urlRegex, function(url) {
        return...