Search code examples
jquery-mobilejquery-validateajaxform

AJAX Form Submission in jQuery Mobile


I'm trying to submit a simple login form via ajax on a jQuery Mobile site but I'm having trouble.

It seems that when I submit the form (via POST), the form parameters are getting added to the url. Not only that, they erase the anchored page I was at before form submission.

For example, I'm on page localhost:8080/myapp/#sign_up

Then I submit the form causing the url to become: localhost:8080/myapp/[email protected]&pass=pass

So if I hit validation errors and click a 'back' button, I don't get returned back to the #sign_up page.

Any ideas?


Solution

  • If you handle form submission with a custom submit event handler you can handle validation on the same page:

    //bind an event handler to the submit event for your login form
    $(document).on('submit', '#form_id', function (e) {
    
        //cache the form element for use in this function
        var $this = $(this);
    
        //prevent the default submission of the form
        e.preventDefault();
    
        //run an AJAX post request to your server-side script, $this.serialize() is the data from your form being added to the request
        $.post($this.attr('action'), $this.serialize(), function (responseData) {
    
            //in here you can analyze the output from your server-side script (responseData) and validate the user's login without leaving the page
        });
    });
    

    To stop jQuery Mobile from running its own AJAX sumbission of your form put this on your form tag:

    <form data-ajax="false" action="...">