0
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample download</title>
</head>

<body>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>

<span id="paperlink">
<a href="https://www.google.com/linktoapdffile.pdf" class="btn btn-danger btn-lrg doajax" >Download</a>
</span>

<script>

function doajax(){
    $.ajax({
    type: "POST",
    url: "https://www.google.com/scripts/custom.php",
    dataType: "text",
    data: {"wp_title": "Multi-Party Orchestration Platform", "cf_company": "MPO"}
    });
}

var link = document.getElementById('paperlink');
link.onclick = doajax();
// $("#paperlink").html('The button was clicked');

</script>

</body>
</html>

I am trying to submit a form to download a pdf file and send some data back to the server using php, json and curl. One button click, two actions. When I load the above, it sends the data regardless of whether the download button is clicked. I would like to only send data if the button is clicked and the download viewed. I cannot add an ID to the button, that's why I added the span with an ID.

Brillon
  • 11
  • 2
  • You're invoking `doajax()` ***immediately*** when the page loads and setting it's returned value as the `onclick` property. The quick fix to this is to provide the function ***reference*** instead: `link.onclick = doajax;`. Far better practice would be to use `addEventListener()` instead of the event attributes: `link.addEventListener('click', doajax);` – Rory McCrossan May 18 '23 at 20:50

0 Answers0