javascriptjqueryhtmlajaxforms

Get form URL without submit


I am a newbie when it comes to jQuery or JavaScript, so apologies if this is an easy one.

Basically, I have a GET form which I need to intercept, meaning I need to call JavaScript instead of actually submitting the form, when the submit button is pressed. I would like to have the complete URL as an output, something like this:

http://server/cgi-bin/status.py?val=1223&val2=434334&val3=4343 

Form

<form class="form-wrapper_2"
      name="myForm"
      onsubmit="return confirm('Are you sure?')" 
      action="http://server/cgi-bin/status.py"
      method="get">
    <input>
</form>

Basically, I need the form to process the URL as if it would submit, but not submit. Main requirement is to send this link via email to the customers so they can track the job progress using this link.

Thanks,
Prince


Solution

  • If you need to process the form with javascript and prevent submitting you need to add a listener on the submit event that will occur on the form when the user presses the submit button. Simply add an id attribute to your form element :

    <form method="get" id="myForm">
    ...
    </form>
    

    Then add the listener :

    <script>
    $(function(){
        $("#myForm').on('submit', function(event) {
            event.preventDefault(); // This line prevents the normal behaviour of the submit button
    
            var queryString = $(this).serialize(); // This will generate a query string like so : "val=1223&val2=434334&val3=4343"
    
            var url = "http://server/cgi-bin/status.py?" + queryString; // Now you have the full URL
    
            // Then you can send an AJAX request to a server-side script that will send the mail
            $.ajax({
                url: 'http://server/cgi-bin/email.py', // Your e-mailing script
                method: 'POST', // or GET whatever
                data: {
                    url: url,
                    email: 'recipient@domain.com'
                },
                ...
            })
    
        })
    })
    
    
    </script>