47

I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).

Basically, I need to check for IsPostBack in JavaScript.

Thank you.

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
roman m
  • 26,012
  • 31
  • 101
  • 133
  • I edited this question to reflect the true intent of roman's original question and which answer he selected as accepted, since there was some confusion as to the platform this question was targeted at. – Jason Bunting Sep 12 '08 at 19:23

10 Answers10

67

Server-side, write:

if(IsPostBack)
{
   // NOTE: the following uses an overload of RegisterClientScriptBlock() 
   // that will surround our string with the needed script tags 
   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 your thing
}

You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
  • 6
    LOL - rehashing? While you were answering, so was I. I had not idea you had answered it (we were only a minute or two apart). It's not like it is that unique of a solution, it is pretty much *the* way to do it. By the way, my comment about yours was an edit after I answered - you can see the history – Jason Bunting Sep 12 '08 at 18:50
  • Btw, you need to include a Script block within your string on RegisterClientScriptBlock, as per MSDN. – FlySwat Sep 12 '08 at 18:55
  • 3
    No, I don't. Maybe you need to read about the overload I used, as per MSDN. :) – Jason Bunting Sep 12 '08 at 18:57
  • Ah, missed the boolean at the end, that will learn me for not scrolling over the code. – FlySwat Sep 12 '08 at 19:00
  • 1
    Jason, put the "overload" explanation in your answer – roman m Sep 12 '08 at 19:03
  • Roman, although I don't think an explanation should be needed, I added it for you. – Jason Bunting Sep 12 '08 at 19:17
  • 1
    This would make it crystal clear for the next person looking for the answer, without having to read through the comments. thanx – roman m Sep 12 '08 at 19:48
  • 4
    By the way, to reach the ClientScript property from code-behind use Page.ClientScript. – md1337 Oct 20 '10 at 19:18
  • 1
    @Roman - I still think it _is_ crystal clear without the overload explanation. Anyone that knows their C# or OOP code knows that methods may very well have overloads. Besides, if they enter the code in as I have it, it will compile. They really don't need the additional information, ideally. Again, I added it, but don't think it was really that necessary. :) – Jason Bunting Nov 24 '10 at 22:39
  • 1
    @Jason Bunting - i thought you got this point across 2 years ago :) – roman m Nov 24 '10 at 22:56
  • LOL. I know, please forgive me - I am a bit anal and I guess I was not sure I was clear _enough_. I am just critical of my own writing at times and wasn't sure my point was as obvious or clear as it could be. Just ignore me! :) – Jason Bunting Nov 24 '10 at 23:17
  • 1
    You can't use if to check for the existence of a variable. Well, you can, but it doesn't work in all browsers. The JavaScript should look like this: if (typeof(isPostBack) != "undefined" && isPostBack). And, as md1337 points out, it should be Page.ClientScript not just ClientScript. – mhenry1384 Nov 02 '11 at 19:40
  • I don't want to reopen an existing discussion, but what's all the fuss about 'should be, needs to be ...' -> This answer was a very good solution to the original question, I don't see why the explanation for signature overload is needed -> Page.ClientScript? I've used ClientScript directly in this case, and it works like a charm, so what's the problem here... – Nathan May 07 '12 at 13:04
29

There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:

if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}

or

if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
Elliott
  • 2,669
  • 2
  • 23
  • 33
Faustin
  • 307
  • 3
  • 2
  • Will not work in external .js file and it's also quite dirty: it's bad to have a dependency on ASP from your Javascript. Makes it not portable. – md1337 Oct 20 '10 at 19:14
  • 23
    I don't agree that this code sucks. If your JavaScript depends on ASP.NET anyway (in my case, it calls PageMethods.* and uses various embedded .ClientID calls to be able to refer to the ASP.NET controls) then that's fine. Furthermore, how are the other examples any more portable? You're referring to a variable isPostBack which, without the accompanying ASP.NET code in the codebehind, would make no sense. – crdx Jan 12 '11 at 08:49
16

hi try the following ...

function pageLoad (sender, args) {

alert (args._isPartialLoad);

}

the result is a Boolean

VladL
  • 12,769
  • 10
  • 63
  • 83
Wily AO
  • 161
  • 1
  • 3
  • 2
    This is the correct answer. Not the others. It uses built-in functionality, works in external .js files and does not require any code-behind implementation. See this post: http://stackoverflow.com/questions/602441/whats-the-different-between-asp-net-ajax-pageload-and-javascript-window-onloa for more – Adam Jul 18 '16 at 08:25
  • Thank You Sir! :) That should be the correct answer. Works both in pure ASP and Telerik (RadScriptManager instead of ScriptManager) – Skipper Jan 11 '18 at 09:39
5

The solution didn't work for me, I had to adapt it:

protected void Page_Load(object sender, EventArgs e)
{
    string script;
    if (IsPostBack)
    {
        script = "var isPostBack = true;";
    }
    else
    {
        script = "var isPostBack = false;";
    }
    Page.ClientScript.RegisterStartupScript(GetType(), "IsPostBack", script, true);
}

Hope this helps.

md1337
  • 1,440
  • 2
  • 16
  • 32
  • 2
    And why didn't it work? Rather than come up with a different solution, maybe you should have dug a bit deeper to find out why it would not work so that you could, at least, post that information here with your adaptation. – Jason Bunting Nov 24 '10 at 22:48
  • 3
    Look, that was a long time ago and I don't remember why it didn't work. I should have posted why, but my time is very limited, so I just posted my fix. Hopefully this will benefit 1 or 2 people, at the risk of incurring your wrath for daring to question your 2 years old solution. – md1337 Dec 02 '10 at 18:55
  • 1
    It didn't work because if you do an "if" on a nonexistent variable, it quits your script (in Firefox 7 anyway). But you don't need to declare the variable if postback is false, you can do this in your JavaScript: if (typeof(isPostBack) != "undefined" && isPostBack) – mhenry1384 Nov 02 '11 at 19:46
2

Try this, in this JS we can check if it is post back or not and accordingly do operations in the respective loops.

    window.onload = isPostBack;

    function isPostBack() {

        if (!document.getElementById('clientSideIsPostBack')) {
            return false;
        }

        if (document.getElementById('clientSideIsPostBack').value == 'Y') {

            ***// DO ALL POST BACK RELATED WORK HERE***

            return true;
        }
        else {

            ***// DO ALL INITIAL LOAD RELATED WORK HERE***

            return false;
        }
    }

2

You could put a hidden input on the page, and after the page loads, give it a value. Then you can check that field, if it was in the post data, it's a postback, otherwise it is not.

There were two solutions that used server side code (ASP.NET specific) posted as responses. I think it is worth pointing out that this solution is technology agnostic since it uses client side features only, which are available in all major browsers.

NerdFury
  • 18,876
  • 5
  • 38
  • 41
  • It is true that your solution is agnostic, but the question, based on the way this was tagged, was specific to ASP.NET. Also, since my response was accepted as the answer, Roman is obviously using ASP.NET – Jason Bunting Sep 12 '08 at 19:20
  • See my comment on why I edited this question to provide more clarity. I left a comment on the original question. – Jason Bunting Sep 12 '08 at 19:23
0

Create a global variable in and apply the value

<script>
       var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>

Then you can reference it from elsewhere

iuppiter
  • 315
  • 3
  • 9
  • Why is this down voted? It seems the simplest answer. Are there any problems if I use this? – Martin Belcher - AtWrk Jun 15 '18 at 09:32
  • I think the downvoters are frowning on a solution that hinges on global scope, which is the easiest to pollute/corrupt accidentally. So, no guarantees that your code will not suddenly start misbehaving. Otherwise, this *is* actually a simple solution I also like. – Water Cooler v2 Dec 28 '18 at 08:15
0

You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.

ctrlShiftBryan
  • 27,092
  • 26
  • 73
  • 78
0

Here is one way (put this in Page_Load):

if (this.IsPostBack)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(),"PostbackKey","<script type='text/javascript'>var isPostBack = true;</script>");
}

Then just check that variable in the JS.

FlySwat
  • 172,459
  • 74
  • 246
  • 311
0

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

<html>

<?php
if ($_POST['myVar']) {
    //postback
    echo '<script>var postingBack = true;</script>';
    //Do other processing
} else {
    echo '<script>var postingBack = false;</script>'
 } ?>
<script>
function myLoader() {
     if (postingBack == false) {
          //Do stuff
     }
 }

<body onLoad="myLoader():"> ...
Ian
  • 4,208
  • 21
  • 33
  • This was an ASP.NET-specific question, but I don't think you should receive a downvote (I don't know who did it) for posting PHP solution - your idea is correct even if the language is not. :) – Jason Bunting Sep 12 '08 at 18:54
  • Admitidly the original question was tagged asp.net, but it was not phrased as such. The problem and all but the accepted answer are language agnostic. The accepted answer is correct in terms of the rephrased question but as with most .net stuff, protects the developer from the underlying mechanics. – Ian Sep 12 '08 at 20:12
  • "Protects the developer from the underlying mechanics?" How so? Maybe you mean to use the word "insulates" instead of "protects." It's not something we need protection against. ASP.NET WebForms, not MVC, is crap, I will admit. It is a leaky abstraction at best. That said, I completely understand the underlying mechanics of the HTTP protocol, HTML, browsers, etc. That isn't the point - you make do with hacks and such when you have no choice about the framework you are working in, which is the case for a lot of software developers that work in the industry. I don't know what you are getting at. – Jason Bunting Nov 24 '10 at 22:52