Daniel Sh.
Daniel Sh.

Reputation: 2074

AJAX / Postback Issue

I've been struggling for the whole weekend with unwanted postbacks.

The popup I'm working on has a button that basicaly fires a few stored procedures and then closes the pop up window. What I wanted to achieve is to have the same result when people hit the X closing buton on the top right. So, X button = myCloseButton.

For that I've done this.

AJAX.

$(window).unload(function(){
var dataToSend = { MethodName: 'UpdateR' };
var options =
    {
        data: dataToSend,
        dataType: 'JSON',
        type: 'POST',
    };
$.ajax(options);
});

.ASPX.CS

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {   #region Ajax methods
              if (Request.Form["MethodName"] == "UpdateR")
              {
                  UpdateRegister();
                  return;
              }
        #endregion
    }
}

And then UpdateRegister() executes the code that I want to execute once people leave the page.

So, the problem comes when people hit another(whatever) control inside the pop up page. The page enters the (!IsPostBack) and the AJAX method. That's understandable since I'm saying on .unload do this and that. (I've tried $(window).bind('beforeunload', function() and it's not working for the desired purpose)

Any idea on "How can I tell the page to difference when it's a closing event like X button or my control, and any other control on the page?" would be much appreciated.

Thanks.

EDIT. It's not something about serializing the form and comparing before leaving. No, it's about logins and stuff, so even if people open the pop up and close it immediately I need to get that.

Upvotes: 0

Views: 422

Answers (2)

Daniel Sh.
Daniel Sh.

Reputation: 2074

In case someone gets here with an error something like this:

Answer: All that was begin a mess in my webform was a button (an asp one). It was postbacking, so I disabled the postback via javascript and that was it. I'm now able to move forward.

Upvotes: 0

irfanmcsd
irfanmcsd

Reputation: 6571

Why not you create WebMethod and directly call instead of calling via Page_Load() page event.

[WebMethod]
public static string UpdateRegister()
{
   // your update register script here
}

Sample call from jquery, you can call this ajax when someone click on load or unload button.

You can call ajax script when button with id "button1" clicked e.g

$(function(){
  $('#button1').click(function() {
    // close window
    window.close();
    // call ajax script to perform server side script

      $.ajax({
      type: "POST",
      url: "Sample.aspx/UpdateRegister",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function (msg) {
      alert(msg.d);
    }
   });   
});
});

Upvotes: 1

Related Questions