views:

82

answers:

3

Hello

I've got a form on the html page which gets submitted by javascript in some cases. The problem is that browser window change its location to the action URL specified for this form. Is there any way to prevent it of working this way?

A: 

Post it with Ajax

Victor
A: 

You can either:

  1. Submit with AJAX
  2. Submit to an iframe
CodeMonkey
+2  A: 

Use a javascript library to submit the form via Ajax (xhr) or submit to iframe

Full Jquery example:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"&gt;&lt;/script&gt;

<script type="text/javascript">
    $(document).ready(function(){
        $('#yourForm').submit(captureSubmit)
    })

    function captureSubmit(event) {
        var frm = $(event.originalTarget);
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function(results) {
                // do stuff
                alert(results);
            },
            error: function(result) {
                // handle the error
                alert(result.status + ' ' + result.statusText);
            }
        });  
        return false;
    }
</script>

<form id="yourForm" action="foo.html" method="POST">
    Name: <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

[EDIT] made example more complete.

Lance Rushing
Is there a way to do this with asp.net ajax?
Vladimir
I'm testing in FireFox and get an error which says "frm.serialize() is not a function". What can I do about it?
Vladimir
You'll need to pull in the jquery library
Lance Rushing
btw, is that ok when result is success and code is 0?
Vladimir
you might get a code of 0 when testing it via file://. But a server (http://) should return a 200 code.
Lance Rushing