2

I'm trying to pass a single parameter to my code behind. I'm reaching the success end of ajax but the method in my aspx.cs code behind doesn't get called. I'm using a masterfile if it makes a difference.

Javascript:

$(document).ready(function () {
    var someID = "";
    $('.glyphicon-trash').click(function () {
        $.ajax({
            type: "POST",
            url: "fileName.aspx/deleteSomething",
            data: "{'deleteSomeID':'" + someID + "'}", // someID is assigned to a value by another button
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert("success"); // this alert works.
            }
        });
    });
});

fileName.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{ 
    //... stuff here
}

[WebMethod]
public static void deleteSomething(string deleteSomeID)
{
    MySqlDbUtilities db = new MySqlDbUtilities();
    MySqlCommand cmd;
    string sql = "DELETE FROM Targets WHERE targetID = @someID";
    cmd = db.GetCommand(sql);

    cmd.Parameters.AddWithValue("@someID", deleteSomeID);

    cmd.ExecuteNonQuery();
    db.Dispose();
}

The "someID" is filled when you click a button on the page. That is working properly, I triple checked. The method however doesn't do anything. I don't know if it's being reached either. Any ideas?

9
  • 2
    Put a breakpoint on the method's signature to see if it's being hit or not Commented Nov 30, 2015 at 14:28
  • @cFrozenDeath I put a breakpoint on the method signature and it was not hit. That's interesting. Commented Nov 30, 2015 at 14:37
  • 1
    Do you see any errors at browser's console? (F12) Commented Nov 30, 2015 at 14:37
  • @zed no errors in console Commented Nov 30, 2015 at 14:38
  • 1
    is 'msg' anything? In your success handler, is this an empty string? In MVC we often return JsonResult from ajax methods - I'll update my answer with something. Commented Nov 30, 2015 at 14:59

3 Answers 3

1

Do not build up the data parameter manually, instead make a proper encoding by using JSON.stringify:

$.ajax({
    type: "POST",
    url: "fileName.aspx/deleteSomething",
    data: JSON.stringify({ deleteSomeID: someID }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        alert("success");
    }
});

Also, you may handle the scenario where your query could throw an exception, and act accordingly in your UI, a very simple way of do this:

[WebMethod]
public static string deleteSomething(string deleteSomeID)
{
    try {
        MySqlDbUtilities db = new MySqlDbUtilities();
        MySqlCommand cmd;
        string sql = "DELETE FROM Targets WHERE targetID = @someID";
        cmd = db.GetCommand(sql);

        cmd.Parameters.AddWithValue("@someID", deleteSomeID);

        cmd.ExecuteNonQuery();
        db.Dispose();
    } 
    catch (Exception e) {
        return e.Message;
    }

    return "1";
}

Then, manage the response at success callback:

$.ajax({
    type: "POST",
    url: "fileName.aspx/deleteSomething",
    data: JSON.stringify({ deleteSomeID: someID }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (response == "1") {
            alert("Successful deletion");
        } else {
            alert("Operation failed! Details: " + response);
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Your data: param looks wrong to me. You don't need it to be a string.

UPDATE: You say you hit the success handler - just for completeness can you add this error handler and double check it is not hit?

$(document).ready(function () {
 var someID = "";
        $('.glyphicon-trash').click(function () {
            $.ajax({
                type: "POST",
                url: "fileName.aspx/deleteSomething",
                data: { deleteSomeID: someID },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert("success"); // this alert works.
                },
                error: function (xhr, status, text) {
                  console.log(xhr.status);
                  console.log(xhr.text);
                  console.log(xhr.responseText);
                 }
            });
        });

I'm more used to MVC, so I cannot guarantee JsonResult works in webforms (I'd be surprised if not though).

Change your webmethod to return a JsonResult.

In your code, declare a bool set to false, and set it to true after your SQL execution. Return the following:

JsonResult returnObj = new JsonResult
        {
            Data = new
            {
                wasSuccessful = myBool,
            },
            ContentEncoding = System.Text.Encoding.UTF8,
            JsonRequestBehavior = JsonRequestBehavior.DenyGet
        };

        return Json(returnObj);

Change your success handler:

success: function (data) {
            console.log(data);
            alert(data.wasSuccessful);
        }

3 Comments

I didn't think it would work without being a string. Thanks. But, it's still giving me the same problem. +1 anyways
I'm still hitting success after adding in your error handling.
@user3044394 you're receiving "msg" in your success function when your method returns void. You should either return something else in your function or remove "msg" from the AJAX call
0

Ajax call to ASP.NET WebMethod not hitting server side, because if you inspected the response by debuggin (msg in your question), you could see the "Authentication failed." Error.

It Resolved by setting AutoDirectMode to Off in App_Start/RouteConfig.cs

settings.AutoRedirectMode = RedirectMode.Off;

and if you use ScriptManager, change EnablePageMethods value to 'true':

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
    </asp:ScriptManager>

please don't forget rate me, if ithis worked (after many searches, this worked for me).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.