何时何时不成功:值在jQuery Ajax方法中执行? (标题位置未更改)

I'm submitting a form using jQuery Ajax.

The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).

Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?

Here's my Ajax code:

$(document).ready(function(){
    $("#button").click(function(){
    **//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
    //var **xy**= $("#digits").val();
    //if(xy!=""){
    $.ajax({
        url: "submitform.php",
        type: "POST",
        data: $('#signupform').serialize(),         
        success: function(result){
            $(location).attr('href', 'login2.php');
            },
            error: function(){
            alert(error);
            }
        });
    //  }
    });
});

Here's concerned input tag:

 <form id="signupform" name="form1" method="post" enctype="multipart/form-data">
            <input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......

Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?

To Question 2:

If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.

You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.

$(document).ready(function() {
  $("#signupform").on('submit', function(e) {
    e.preventDefault();

    //FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
    //var **xy**= $("#digits").val();
    //if(xy!=""){
    $.ajax({
      url: "submitform.php",
      type: "POST",
      data: $('#signupform').serialize(),
      success: function(result) {
        $(location).attr('href', 'login2.php');
      },
      error: function() {
        alert(error);
      }
    });
    //  }
  });
});

When you use jquery ajax there is two types of result:

400 - OK status which be capture by the success function 402 or 500 are internal errors and those will be capture by the error function.

Now, in your error function youre trying to print an error variable that does not exist.

Also, when you use preventDefault you have pass variable that handles de event too cancel.