Ajax call always returns 500 client-side error

I am trying to send data back to a web method located in Default.aspx

Jquery code:

data = "{'saveData':'testtestest'}"

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/Default.aspx/SavePins",
        data: data,
        dataType: "json",
        success: function (response) {
            if (response.d) {
                //    var obj = JSON.parse(response.d);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $('#modalContentBox').html('Whoops! There was an error saving!').removeAttr('class').attr('class', 'alert alert-error');
            $('#myModal').modal();
        }
    });

Web method:

[WebMethod]
public bool SavePins(string saveData)
{
    try
    {
        File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"), saveData);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}

The problem is that the Ajax call always returns a 500 error to the client side. This is actually not a message to the server. There is an element <form>c runat="server"on the page. I added<asp:ScriptManager EnablePageMethods="True" runat="server"/>

+2
source share
1 answer

You need ScriptMethod for your web method, because you need to send the response as json.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]      
public bool SavePins(string saveData)
{
     try
      {
           File.WriteAllText(string.Format("{0}{1}.shane", file_location, "pinsData"),     saveData);
           return true;
      }
     catch (Exception)
     {
        return false;
      }
 }
+6
source

Source: https://habr.com/ru/post/1727777/


All Articles