0

The problem is: I have custom analtyics engine that sends log using JavaScript. I want to send log after user submits a form. The log is send using AJAX. Now the problem is, form submission is not AJAX, it is normal request that refreshes the page.

I already learned that you can force the script executions even if client aborted connection

Does php execution stop after a user leaves the page?

What I want to learn is how to be sure that server recives request and headers if form is submited almost instantly after AJAX call is send?

Community
  • 1
  • 1
Szymon Cofalik
  • 1,142
  • 8
  • 9

2 Answers2

0
var url = "...";
var my_form = document.getElementsByTagName("form")[0];
var request_received = false;

my_form.addEventListener("submit", function(e) {
    if (!request_received) {
        e.preventDefault(); // prevent the form from submitting

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState >= 2 && !request_received) {
                request_received = true;
                my_form.submit(); // submit the form only if the request has been received
            }
        };
        xhr.open("GET", url, true);
        xhr.send();

        return false;
    }
}, false);
Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
-1

Lets say that this is your form with submit button:

<form id="myForm" action="/myAction.html" method="POST">

    <!-- form inputs -->
    <input type="submit" value="submit me!" />

</form>

With JavaScript you can bind to the submit event of your form, do your ajax call and then return true to continue submiting your form to the server:

<script type="text/javascript">

document.getElementById('myForm').addEventListener('submit', function(e){
    // do your ajax call here and when you finish, return true from
            // this function (in the ajax success callback)
    return true;
});

</script>
udidu
  • 8,269
  • 6
  • 48
  • 68