0

My issue is I need to POST XML data to a payment gateway.

I've tried to follow the answer from PHP Redirect with POST data, but I need to intercept the submit to manipulate the data.

So, I've tried the following:

<html>
<form id="myForm" action="<?php echo $url; ?>" method="post">

</form>
<script type="text/javascript">
$(document).ready (function () {
    document.getElementById('myForm').submit();

    $('#myForm').submit(function (e) {
        console.log('A');

        e.preventDefault();

        alert("a");

        $.post("<?php echo $url; ?>", {'data': formxml}, function (data) {
            // callback logic
        });
    });
});
</script>
</html>

However, it doesn't work as I expected it to be.

When I do the document.getElementById('myForm').submit(), I expected the $('#myForm').submit will intercept it and I can do data validation.

How should I proceed with it in order to achieve my expected result?

David Yap
  • 79
  • 2
  • 12

2 Answers2

1

Quick pointer - Javascript is interpreted line by line. Meaning line one gets executed before line 2.

In your case, the following line:

document.getElementById('myForm').submit();

is getting executed before:

$('#myForm').submit(function (e) {
    console.log('A');

    e.preventDefault();

    alert("a");

    $.post("<?php echo $url; ?>", {'data': formxml}, function (data) {
        // callback logic
    });
});

Thereby resulting in the submit() to be triggered much before your handler has had a chance to be bound to the form.

Try interchanging them. The following code works:

<html>
<form id="myForm" action="<?php echo $url; ?>" method="post">

</form>
<script type="text/javascript">
$(document).ready (function () {
    $('#myForm').submit(function (e) {
        console.log('A');

        e.preventDefault();

        alert("a");

        $.post("<?php echo $url; ?>", {'data': formxml}, function (data) {
            // callback logic
        });
    });

    $('#myForm').submit();
});
</script>
</html>

Let me know if that is not the result you were expecting.

Sunny R Gupta
  • 5,026
  • 1
  • 31
  • 40
0

The problem is that you are using vanilla JavaScript to trigger your submit while your event listener is set up by jQuery. Change

document.getElementById('myForm').submit();

to

$('#myForm').submit();

and you should see the expected result.

Henrik Erstad
  • 681
  • 3
  • 11
  • 21