0

i want to call the unlock method on closing or redirecting other page, so i have used ajax call. but the method unlock is not firing. please let me know what i am doing

 [WebMethod]
public void Unlock()
{
    CreateProject_BL _objcreatebl = new CreateProject_BL();
    _objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}

  function HandleOnclose() {
        $.ajax({
            type: "POST",
            url: "ProjectDetails.aspx/Unlock",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        });
    }
window.onbeforeunload = HandleOnclose;
praveen
  • 11
  • 2
  • Just wanted to a check a few things, have you ensured Unlock function is indeed part of ProjectDetails.aspx ? Also, ProjectDetails.aspx is in the same domain as the file where HandleOnClose sits? – snit80 Sep 27 '16 at 06:32

2 Answers2

0

Where you passing project_id in your ajax call??? pass project_id in your method

 [WebMethod]
public void Unlock(string project_id)
{
    CreateProject_BL _objcreatebl = new CreateProject_BL();
    _objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}

and then rewrite ajax call as

function HandleOnclose() {
        $.ajax({
            type: "POST",
            url: "ProjectDetails.aspx/Unlock",
            contentType: "application/json; charset=utf-8",
            data : "{project_id:'1234'}",
            dataType: "json"
        });
    }
window.onbeforeunload = HandleOnclose;
BornToCode
  • 207
  • 2
  • 7
0

There's a couple of issues. Firstly your WebMethod expects a querystring parameter, yet you're sending a POST request and you also don't send any data in the request. You should provide project_id as a parameter in an object to the data property of the AJAX request.

Also note that sending an AJAX request in the onbeforeunload event is one of the very few legitimate cases where you need to use async: false to stop the page from being closed before the AJAX request completes. Try this:

[WebMethod]
public void Unlock(string projectId)
{
    CreateProject_BL _objcreatebl = new CreateProject_BL();        
    _objcreatebl.upd_lockedBy(Convert.ToInt32(projectId), "");
}
function HandleOnclose() {
    $.ajax({
        type: "POST",
        async: false, // only due to running the code in onbeforeunload. Never us it otherwise!
        url: "ProjectDetails.aspx/Unlock",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { projectId: '1234' }
    });
}
window.onbeforeunload = HandleOnclose;

Also note that depending on the browser you may be restricted from sending an AJAX request in the onbeforeunload event at all. See this question for more details.

Community
  • 1
  • 1
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339