-2

I am calling my static web method from html page using ajax. but it doesn't hit my method rather it reload the page. My script is below

$(document).ready(function() {
          $("#btnSave").click(function () {
              alert("Clicked");
              var name = $("#txtFirstName").val();
              alert(name);
        // do the extra stuff here
          $.ajax({
          type: "POST",
          url: "AddEditStudent/SaveData",
          data: '{name: "' + name + '" }',

          success: function() {
          //$('.simple-sucess').fadeIn(100).show();
          //$('.contact_form').fadeOut(100).hide();
          // $('.simple_error').fadeOut(100).hide();

          },
          failure: function () {
              alert("fail");
          }

and my code behind method is

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {

    }
}


[WebMethod]
    public static string SaveData(string name)
    {
        return "hello";
    }

1 Answer 1

1

The problem here is that you didn't prevent the default action of the form when you clicked the submit button which is why it still reload the page.

To fix it, use e.preventDefault();

And instead of triggering the ajax on button clicked, you should trigger it once the form is submitted.

e.g.

$(document).ready(function() {
  $("#yourForm").submit(function(e) {
    e.preventDefault();
    alert("Submit");
    var name = $("#txtFirstName").val();
    alert(name);
    // do the extra stuff here
    $.ajax({
      type: "POST",
      url: "AddEditStudent/SaveData",
      data: '{name: "' + name + '" }',
      success: function() {
        //$('.simple-sucess').fadeIn(100).show();
        //$('.contact_form').fadeOut(100).hide();
        // $('.simple_error').fadeOut(100).hide();
      }
    });  
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it changed the error message to resource: the server responded with a status of 405 (Method Not Allowed)
@AliKhan Then it means it is now successfully communicating with the server. That 405 response you're having I believe is another issue now which you can find the answer here

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.