Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for IsPostBack in JavaScript? [duplicate]

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.

like image 756
roman m Avatar asked Sep 12 '08 18:09

roman m


2 Answers

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.

like image 52
Jason Bunting Avatar answered Oct 06 '22 09:10

Jason Bunting


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} 
like image 27
Faustin Avatar answered Oct 06 '22 08:10

Faustin