Learner_Programmer
Learner_Programmer

Reputation: 1299

how to use jquery validation plugin to submit a form using ajax and redirect to another page after success

i'am trying to ajax submit a form to controller function and then redirect it to the page containing list on success, since i'am using jQuery validation plugin, i had to ajax submit like this

submitHandler: function (form) {
    $.ajax({
        type: "POST",
        url: "/admin/student/addstud",
        data: $('#sturegister').serialize(),
        //dataType: "html",
        success: function (response) {
            window.location.replace('/admin/student/add');
        }
    });

The details are added to the db, however, the form is not redirecting to /admin/student/add.is there any other way to do this ? thanks.

Upvotes: 0

Views: 1106

Answers (2)

Sparky
Sparky

Reputation: 98718

There's pretty much no point in using ajax if you want to redirect to a new page... that's like taking the bus when you really want to walk. If you want to walk, just walk.

Simply use the action to point to the URL of your server-side script...

<form action="/admin/student/addstud" ...

... and then handle the page redirect from server-side. (That's how this used to be done before we started using ajax.)

Then you can totally remove the submitHandler callback function from .validate(), as the default behavior of jQuery Validate is to just submit the form (action) after the form passes validation.

Upvotes: 1

Bud Damyanov
Bud Damyanov

Reputation: 31829

The location.assign() method loads a new document.

window.location.assign("http://www.your-full-url-here.com");

or

window.location.href ="http://www.your-full-url-here.com";

One notice: the success method of jQuery AJAX call is a function to be called if the request succeeds, but this does not mean, that the user data is inserted correctly into database, it means only that user browser have sent data to your server. What happens next - it is up to you.

Upvotes: 0

Related Questions