27

How to detect/track/check postback in javascript(e.g in asp.net Page.isPostBack())? Any suggestion?

o.k.w
  • 25,490
  • 6
  • 66
  • 63
Subrat
  • 881
  • 1
  • 11
  • 19

11 Answers11

42

ASPX:

<input type="hidden" id="_ispostback" value="<%=Page.IsPostBack.ToString()%>" />

Client-side Script:

function isPostBack() { //function to check if page is a postback-ed one
  return document.getElementById('_ispostback').value == 'True';
}

PS: I have not tested it but I've done somthing similar before and it works.

LbISS
  • 623
  • 2
  • 10
  • 25
o.k.w
  • 25,490
  • 6
  • 66
  • 63
  • 1
    As a matter or preference I add runat="server" to the hidden input and change it's value in the codebehind file but this works just fine. And I would recommend jQuery to do the javascript because that would become: function isPostBack() {return $("#_ispostback").val() == 'true';} – Robert Massaioli Dec 07 '09 at 03:31
  • @Shhnap: Yes I agree. Just a lazy way out for me :P – o.k.w Dec 07 '09 at 03:34
  • 7
    Why bother inserting an `` element? You could just have isPostBack() directly return the value of Page.IsPostBack: `return <%= Page.IsPostBack %>;` – RickNZ Dec 07 '09 at 10:23
  • @RickNZ: That's a pretty good idea. Post as answer, I'll up-vote it :) – o.k.w Dec 07 '09 at 10:47
  • Sure: I added it to my earlier answer. – RickNZ Dec 07 '09 at 11:12
  • 6
    There is a reason why a hidden field is better, just using a javascript function will only load this value on actual post back, but for asynch postback it will not, using an input field within a an update panel that is set to updatemode=always, will make this work even on asynch postbacks. – Shrage Smilowitz Jul 28 '10 at 23:09
  • This falls down when code-blocks aren't allowed. What would you do in that instance? – Code Maverick Aug 08 '17 at 20:13
  • Slight variation for culture and language invariance `<%=Page.IsPostBack ? "true" : ""%>` ..... which enables javascript to be more succint too `if (document.getElementById('_ispostback').value) doStuff();` – James Westgate Nov 01 '17 at 10:55
22

In some cases, you may want to check for postback without any server-side code. For example, in SharePoint, you cannot have code blocks in SharePoint Designer pages, so you can't use any solution that requires <%=something %>. Here is an alternative that involves no server-side code:

<script type="text/javascript">
 function isPostBack()
 {

  return document.referrer.indexOf(document.location.href) > -1;
 }

 if (isPostBack()){
document.write('<span style="color:red;">Your search returned no results.</span><br/>');
 }
 </script>

One caveat (or feature, depending on how you look at it), this will detect not just postbacks, but any instance where the page links to itself.

Daniel
  • 3,021
  • 5
  • 35
  • 50
9

If you want to check whether the current page will be a postback if the user clicks on a submit button, you can check for the presence of ViewState:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="xxxxx" />

You can use something like document.getElementById("__VIEWSTATE") or the jQuery equivalent.

However, if you want to see whether the current page was generated in response to a postback, then you need to insert that data into the page on the server side first.

For example:

function isPostBack() {
  return <%= Page.IsPostBack %>;
}
RickNZ
  • 18,448
  • 3
  • 51
  • 66
  • This falls down if you don't have access to server-side code and code blocks aren't allowed. – Code Maverick Aug 08 '17 at 20:11
  • Oddly, that does not work for me but this does: function IsPostBack() { var ret = '<%= Page.IsPostBack%>' == 'True'; return ret; } – Zeek2 Oct 13 '17 at 12:21
6

As JavaScript shouldn't be written with server-side code, and injecting new elements into the page seems like overkill, it seems to me that the simplest solution is to add [datat-*] attributes to the <head> element:

In Page_Load:
Page.Header.Attributes["data-is-postback"] IsPostBack ? "true" : "false";

This can then be accessed as:

jQuery:
$('head').data('isPostback');
Vanilla JS:
document.head.getAttribute('data-is-postback') === 'true';

Of course, if you treat the [data-is-postback] attribute as a boolean attribute, you could alternatively use:

In Page_Load:
if (IsPostBack)
{
    Page.Header.Attributes.Add("data-is-postback", "");
}
else
{
    Page.Header.Attributes.Remove("data-is-postback");
}
jQuery:
$('head').is('[data-is-postback]');
Vanilla JS:
document.head.hasAttribute('data-is-postback')
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • While this is great if you access to server-side code, it falls down if you don't. Some software doesn't even allow code blocks, so a pure JavaScript solution would be needed. – Code Maverick Aug 08 '17 at 20:08
5

I have a solution that worked for me.

// Postback catch
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
    alert("post back");
});
user4640122
  • 51
  • 1
  • 1
4

See following:

<script type="text/javascript">

function invokeMeMaster() {

var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';

if (chkPostBack == 'false') {

alert('Only the first time');

}
}



window.onload = function() { invokeMeMaster(); };

</script>
Brij
  • 6,086
  • 9
  • 41
  • 69
0

You can only keep track of the postback if you are using AJAX requests or have a hidden field of some sort that the javascript reads on page load. Otherwise the page is regenerated and all POST data is lost; as you would expect and hope.

Robert Massaioli
  • 13,379
  • 7
  • 57
  • 73
0

on Page_Load on your server-side : The following uses an overload of RegisterClientScriptBlock() that will surround our string with the needed script tags

Server-Side

if (Page.IsPostBack){
   ClientScript.RegisterClientScriptBlock(GetType(),
            "IsPostBack", "var isPostBack = true;", true);
}

Then in your script which runs for the onLoad, check for the existence of that variable.

if (isPostBack){
   //do something here
}
Lequoa
  • 11
  • 2
0

This should work for ASP.Net pages without relying on a backend supplied variable/control:

function isPostBack(frmID) {
    var eventtarget = "";
    var eventargument = "";

    if (!!frmID) {
        if (document.forms.length == 0) return false;

        sForm = document.forms[0];
    }
    else {
        sForm = document.getElementById(frmID);

        if (!sForm) return false;
    }

    if (sForm.__EVENTTARGET) eventtarget = sForm.__EVENTTARGET.value;
    else return false;

    if (sForm.__EVENTARGUMENT) eventargument = sForm.__EVENTARGUMENT.value;
    else return false;

    if (eventtarget != "" || eventargument != "") return true;
    else return false;
}
0

This is a simple JS way to determine the status of IsPostBack that I just got working in the Body of my ASPX page; needed to cause a PostBack during PageLoad for a project.

    <script type="text/javascript">
        if ('False' === '<%= Page.IsPostBack.ToString()%>') 
        {
            __doPostBack();
        }
    </script>
-1

Here is solution using jQuery:

$("a[href^='javascript:__doPostBack']").click(function () {
    alert('ok');
});
Mishami
  • 470
  • 4
  • 4