0

Iam using MVC4, i want to post my page from client to server, iam using ajax post method to post my submit my data.

$("#btn").click(function(){
    $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '/Admin/Create/',
                //data: JSON.stringify(datatosend),
                crossDomain: true,
                dataType: "json",
                success: function (data) {
                    if (data.redirectUrl != null) {
                    window.location = data.redirectUrl;
                    }
})
});

Here instead of <input type="submit" value="add"> am using <input type ="button" value="add" id="btn"> and on click method to call ajax post. When am using submit type, validation are working fine, but on button type vaidations are not working and page is not redirecting after success also. I have seen lot of posts regarding this issue. But not able to find out the reason

2 Answers 2

1

In your click handler do something like:

var isValid = $(this).closest("form").validate();
if (isValid) {

    // do ajax post
}

Or, you can take a look at the documentation, it has a different approach:

http://jqueryvalidation.org/validate

Sign up to request clarification or add additional context in comments.

Comments

0

1 .To fire validation error you can do the following code.

$("#btn").click(function(){


var form = $("#myform").validate();

if(form.valid())
{
    $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '/Admin/Create/',
                //data: JSON.stringify(datatosend),
                crossDomain: true,
                dataType: "json",
                success: function (data) {
                    if (data.redirectUrl != null) {
                    window.location = data.redirectUrl;
                    }
                error: function (errorResponse) {
                    alert(errorResponse.responseText);
                    }
           })
}

});

2.Why your page is not getting redirected check few point .

  • check you are returning Json result from you action as JsonResult.
  • value should be in quotes window.location = '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.