views:

10559

answers:

7

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.

+1  A: 

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
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
See my comment on why I edited this question to provide more clarity. I left a comment on the original question.
Jason Bunting
A: 

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
A: 

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
All you did was take my answer, and remove the else clause.
FlySwat
Very close, but Jason had more details - up vote for you
roman m
Again, I didn't see your answer until I posted mine. And then I saw yours, and edited mine. Get a life.
Jason Bunting
It's not like there is a contest I am trying to win - what motivation would I have for copying your answer? Don't flatter yourself.
Jason Bunting
By the way, the other proof I didn't copy yours is that you forgot about the script tags originally. If you look at my answer, I am using an overload of RegisterStartupScript which will include that automagically. :)
Jason Bunting
No hard feelings, huh?
Jason Bunting
+15  A: 

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
Thanks for rehashing my exact answer...
FlySwat
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
Btw, you need to include a Script block within your string on RegisterClientScriptBlock, as per MSDN.
FlySwat
No, I don't. Maybe you need to read about the overload I used, as per MSDN. :)
Jason Bunting
Ah, missed the boolean at the end, that will learn me for not scrolling over the code.
FlySwat
Jason, put the "overload" explanation in your answer
roman m
Roman, although I don't think an explanation should be needed, I added it for you.
Jason Bunting
This would make it crystal clear for the next person looking for the answer, without having to read through the comments. thanx
roman m
By the way, to reach the ClientScript property from code-behind use Page.ClientScript.
md1337
A: 

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
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
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
+1  A: 

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}
Faustin
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
+2  A: 

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