user3044394
user3044394

Reputation: 135

Ajax call to ASP.NET WebMethod not hitting server side method

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?

Upvotes: 2

Views: 7340

Answers (2)

zed
zed

Reputation: 2338

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);
        }
    }
});

Upvotes: 1

VictorySaber
VictorySaber

Reputation: 3164

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);
        }

Upvotes: 1

Related Questions