tags:

views:

915

answers:

3

On my page I have forms which default to .hide() when the page is loaded. These two forms are account creation and login. They are shown to the user once they click the appropriate link (.show()).

Obviously, if there is a failure with either form, I'd like for the form to stay open instead of hiding after the page loads from submitting.

Right now the forms are using simple html form posting to reach the database. Would there be a better way to do this with jquery, which isn't too complicated? (i'm still fairly new to it, but learning)

Thanks

A: 

I would try the jQuery Form Plugin. It allows you to post a form using ajax.

On success, you can re-direct the browser to where it normally would have gone to on submit.

On error, you can display an error message and keep the user on the form.

jonstjohn
I tried using this not long ago but got confused at one point - may take another look. Thank you.
scrot
+2  A: 

You can assign a handler to the 'submit' action of a form and do whatever you like with it. Send it asynchronously, remove the form again, leave it there, whatever. Here's a starting point:

$('#myloginform').submit( function() {
  var form = $(this);
  $.post(
    form.attr('action'),
    form.serialize(),
    success: function( response ) {
      // do something when all is well
      form.hide();
    },
    failure: function( respones ) {
      // do something when everything explodes
      form.addClass('error');
    }
  );
  return false; // don't fire the regular handler
} );

The jQuery API documentation will give you further details on both the submit (and similar) handler as well as $.post and friends.

edit: This code should go into your $(document).ready handler, I assume you already have your shows and hides in there.

thenduks
A: 

Assuming you can't use ajax, add something to the URL or body of the page that says an error occurred. Then do something like ..

jQuery(document).ready( function()
{
  if(form_error) // check for the error in some way (query_string, a div with an 'error class'
  {
    jQuery('.form-selector').show();
  }
});
james