Run Javascript before Page_Load event - javascript

I have the following JS, currently it's just before my closing body tag
<script type='text/javascript' src='https://www.mydomain.com/jtrack.js'></script>
<script type='text/javascript' >
if (typeof trackPage == 'function') trackPage();
</script>
Part of this script sets a cookie, which I need to read in the Page_Load event of my asp.net page. But that event is firing before the cookie is set. How can I change this so the script runs first?
Thanks

Simple answer, you can't. It is technically impossible.
If you look at the ASP.NET page lifecycle overview then you'll see that the page load event occurs before the page begins to render - which would make it completely impossible for the client to have executed JavaScript on the page at this point, the user agent (browser) hasn't even began to have received the page. With the sole exception of unload, all of the ASP.NET page lifecycle events happen on the server and before any response has been sent to the user.
The unload event is highly unlikely to ever execute after your JavaScript, unless you are streaming a response to the user, had the JavaScript (without dependencies) at the first possible point on the page, and were building a really complicated page response. Even if the JavaScript did somehow execute before the unload event fired, it wouldn't matter, as cookies are sent with the page request and that has already happened. The cookie will not be sent until the next request from that domain (although it doesn't have to be a page that is requested, images, scripts or stylesheet requests will all include the cookie in their request headers).
You can have your JavaScript set the cookie on the first request which will then be available to all subsequent requests in the Load event handler, and use an Ajax request (if necessary) to log that initial page and the assigned cookie value - which will be sent (assuming it has been set at that point) in the headers for the Ajax request.
What you can't do is set a cookie on the browser of a user before the user has visited your site, execute JavaScript before it has been sent to the user, or send new request data part way through a response.

Use JS setTimeout
Eg.
ScriptManager.RegisterStartupScript(this, this.GetType(), "TestMessageModal", string.Format("setTimeout(function(){{swal('{0}','{1}');}},{2});", type, CommonUtils.RemoveSpecialCharacters(Message), timeout), true);

Related

Is it possible to make a HTTP POST to a standard ASP.Net Web Form using XMLHttpRequest/FormData?

Let's suppose we have an ASP.Net Web Form, Page.aspx, in which we do the following:
<script>
$(document).ready(function () {
// grab the standard ASP.Net form
var form = document.forms['ctl01'];
form.addEventListener("submit", function (event) {
event.preventDefault();
sendData(form);
});
});
function sendData(form) {
const xhr = new XMLHttpRequest();
const fd = new FormData(form);
xhr.addEventListener("load", function (event) {
document.open();
document.write(event.target.response);
document.close();
});
xhr.addEventListener("error", function (event) {
alert('Error!');
});
xhr.open("POST", "Page.aspx");
xhr.send(fd);
}
</script>
The reason for this setup is I want to take advantage of the XMLHttpRequest progress event to erm, show some progress indication because the postback may include files that take some time to upload.
The load event handler works great. As a result of the POST I get the contents of Page.aspx again and replace my current document. So it seems that some kind of POST actually does happen BUT, there is one problem. In Page.Load(), the Request.Form and Request.Files collections are empty so I can't process the form/files.
I tried adding the following header but without much luck:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Do you think it is possible to make a successful POST (with page receiving data) using XMLHttpRequest/FormData, or is there some fundamental limitation that prevents this from happening for ASP.Net pages?
Thanks!
Well any ajax call simply can run some code behind, but since the web page IS STILL sitting on the client side in the browser, then things like controls and the page state are NOT available.
So you don’t want a post back, but now you asking for a post back? (I am confused). I mean, either you post back the whole page (standard event post back). Or you drop the controls and things in question into a update panel, and then ONLY that part of the page is posted back. I fail to see any advantage of trying to send “more” of the page in a ajax call when the WHOLE idea is to NOT send the page in the first place, right?
I mean, if you need some extra values in the ajax call, then you have to get/grab those bits and parts from the page, and include that information in your ajax call. (perhaps as a json string).
Without a post back, then viewstate and all of the controls are STILL just sitting on the users desktop in the browser. The code behind, and even the page class object + code ARE OUT OF scope at this point in time. Only upon a post-back does the WHOLE page travel up to server - code behind runs - you have use of full controls on the page, and THEN the whole page travels back down to the client side (and this quite much means that JavaScript code will have to re-start!!!
However, if you need a few parts and values in a page and don't want a full post-back? Then simply put those parts into a update panel. you can then in JavaScript for example do this:
varMyAspNetButton = docuement.GetElementById("Button1");
varMyAspNetButton.Click();
The above will save you world poverty and not have to wire up a bunch of js and web methods since the js code simply CLICKS on your button (that is inside the update panel). In this case, of course a whole page post back does NOT occur, but the page load and events do in fact fire - these so called "partial" page post backs means that the code behind is LIMITED to the information (controls) inside of that up-date panel.
However, as noted, if you do a post back, then the browser page NOW travels up to the server - and that quite much means any js code client side is toast and now can't run, since a whole NEW fresh copy of the web page is about to travel down to the client side again - and that re-starts your js code.
As noted, you can do a partial page post back with a update panel. And in js you can fire a "click" or in fact MOST events of asp.net controls on that page with js.
But, then again?
You don't want a full page post back, and you likely don't want all of the controls and the whole page to travel up to the server. But then again you wondering why you can't use or access controls on the page with ajax calls? Well as noted, the server side code behind is OUT of scope and OUT of context when you make ajax calls. The web page does NOT exist server side. We don't know if the user turned off their computer, or will never do anything in that client side browser and web page. The server at that point in time has lost ALL KNOWLEGE of that web page. So any ajax call does not have use of the controls on the page, and does not even have use of viewstate either.
This tends to mean that say when using say a ajax system to up-load files? Well, you can't store the status in the web page server side - since the page DOES NOT really exist at that point in time. So you can call some web methods, and about the ONLY way to keep some values in context is to use session(), since that does not need the web page, or the view state to function and work.
The major down side of session() of course is that if some user has two tabs open or even two different browsers open? Well, session() is SHARED between those pages - so while session() is great, it also shared between ALL copies of web pages for that given user - and thus you need to add code to separate out each session "set" of values, or simply hope that the user will not have two pages in operation for such file up-loads.
But to answer your question?
You can do and achieve partial page pushbacks by using a up-date panela And thus you can have timer code or js code client side to continue to run since a full page life-cycle does NOT occur. In other words, you control what part of the web page will and is sent up to the server side by using a update panel.
If you don't use a up-date panel, then any ajax calls you make WILL have to pass the data from the browser side, since it STILL just sitting on the users desktop, and any code behind can't grab, nor reach out, or see or even KNOW that the web page exists client side.
So you either pass extra values from the web page with your ajax calls OR YOU can use a update panel, drop controls inside and then the partial page post back will ONLY send up and have use of what you want inside of that panel. So you have two really great choices.
And in either case (a full page post back) or a partial one?
Grab a reference to the client side asp.net button, and fire off a .click event. You can I suppose wire up all kinds of _doPostBack in js, but with update panels and the click() trick, then you have a choice of how much of the page gets sent up, and it all quite much automatic wired up for you and saves a TRUCKLOAD of work that you would have to manually write and wire up if you don't use a update panel to control this.
So you get that "partial" page post back, and in that case the code and events inside of that up-date panel can update/see/use/modify controls in that up-date panel, but anything outside of that up-date panel will NOT have traveled up to the server.
And if you don't use a update-panel, then any ajax call is just that - a direct call to the server side - but the web page STAYS client side - thus on-load and any of the controls or objects or in fact the WHOLE class form object that represents that web page IS STILL SITTING client side - thus as noted, no on-load, no code behind can touch or even see or know about the values of controls on that page, and as noted there is also no ViewState either.
The WHOLE idea of ajax calls is that you did not want and never did want the page to travel up to the server, and then be re-rendered, and then re-sent back down to the client side. But you need to be 100% crystal clear here:
Without a page post back (or partial one with update panels), then the web page does NOT exist any more server side. Web pages are state-less and once the round trip has occurred (web page up to server - code behind runs, page sent back to client), then as far as the server is concerned (and you the developer) that web page is GONE and DOES NOT exist anymore at all - it is out of scope and from your point of view (and the server point of view) that web page does NOT exist anymore the instant it been sent back down to the client side. As noted, the only exception that is practical here is session() values - since they are not part of any given web page.
So, you have to decide if you want a partial page post back to get at and modify some values with server side code.
Or you pass the values with your ajax calls and the returned values can then update the browser controls. And of course once you do eventually do that say full page post back, then the code behind can certainly see + use any controls that the client js code changed - but can only do so with that full page post back, or as noted, controls limited to a update panel if we are talking about a partial page post back (update panel).
You either have to include additional data in your ajax calls, or consider using a partial page post back to send up part of the web page if you need to modify that part of the page with code behind. Or as noted, return information with your ajax call, and then update the client side. There not really a in-between choice here.

Listen to Http server-side Request (document type) Events via Javascript

I am trying to show a gif or message at the moment user click on the link or change URL to send a request to server-side (no ajax call). My reason is: some pages take some seconds to be processed and it would be better user see a loading message while the request is processing.
I tried to listen to server-side events. I checked chrome how it works and captures this kind of requests.
chrome differentiate these types of requests with others base on the document type.
My exact question is: How can I capture/listen to the HTTP request with document type via Javascript at the moment of sending the request to server?
I found the solution with using window.onbeforeunload() function. this event rise whenever any refresh or load happens.
window.onbeforeunload = function (evt) {
console.log("onbeforeunload Call listen to refresh event on _layout page.")
ShowWaiting(true);
}

Browser locks during server side expensive process from async request

So I have a quite expensive and complex PHP process which makes its execution long lasting, lets call it function "expensive_process()".
I have an interface which through a press of a button calls an ajax request to a PHP script which in turn initiates "expensive_process()". Here's the javascript code:
$('#run_expensive_process_button').click( function(){
var url = "initiate_expensive_process.php";
$.ajax({
url: url
});
});
And initiate_expensive_process.php code:
<?php
session_start();
run_expensive_process();
?>
Simple and trivial. Now the issue with this is that while expensive_process() is running, the browser is losing the ability to navigate the domain. If I refresh the browser window it hangs indefinitely while the process last. If I redirect to a different url under the same domain, same thing. This happens in all browsers. However, if I relaunch the browser (close and open a new window, not a tab), navigation works normally, even though expensive_process() is still running.
I've inspected network traffic, and the HTTP request to initiate_expensive_process.php doesn't get a response while expensive_process() is running, but I'm assuming this shouldn't be locking the browser given the asynchronous nature of the request..
One more thing, which I believe is relevant. This situation is happening on a replica server. On my local machine, where I run WAMP and the same source code, this is not happening, i.e., while expensive_process() is running, I'm still able to navigate the hosting domain without having to relaunch the browser. This seems to be an indication of a server configuration problem of some sort, but I'm not sure I can rule out other possible reasons.
Anyone know what might be causing this or what can be done to figure out the source of the problem?
Thanks
Most likely the other PHP scripts also session variables. Only one script process can access a session at a time; if a second script tries to access the session while the first script is still running, it will be blocked until the first script finishes.
The first script can unlock the session by calling session_write_close() when it's done using the session. See If call PHP page via ajax that takes a while to run/return (and it sets session variables), will a 2nd ajax call see those session changes? for more details about how you can construct the script.
I wonder whether it might be due to ajax. The javascript is being executed client-side.
Maybe you might consider a stringified JSON call instead of ajax?

Perl CGI redirect after authentication

I know its a basic question and it is been asked for several times but i was not able to understand it.
I was using a html webpage with some input fields and submit button when the submit button is pressed the post is done through XMLHttpRequest and CGI script is called. In cgi script the authentication is checked with the value in the file of server.
The problem is that if the authenication is false i want to redirect the browser to the xmltest.shtml for this i have written in the CGI:
if($isauthenticated == 0)
{
print "Location: http://xmltest.shtml\n\n";
}
But when this cgi is called in return the get is called with the xmltest.shtml page but the browser is not redirected.
It means that if I check in the Firebug console the get request is seen by me for the xmltest.shtml but the browser page is not redirected to the xmltest.shtml it remains to the same page.
You can't cause the page to redirect that way. When you use XMLHttpRequest, you are sending the redirect header to the XMLHttpRequest client, which runs in the background. You will successfully redirect that client, but it will not affect the page on the screen.
If you want to redirect the actual browser page in response to an XMLHttpRequest session, you will need to write some JavaScript to capture the error condition and redirect the browser by updating the value of document.location.href.
If you're using an AJAX framework like jQuery, there is an error callback available in the ajax method which will get executed if your failed request returns an HTTP 403 or similar.

How to return a "noop" document over HTTP

I have a CGI script that does a lot things. I'm trying to keep the script very simple and portable. I just need some way for the user to send a message to the server without having to lose the current page. So far, I have the following process:
User loads a "status page" from a CGI script.
The status page has a javascript timer that will read data (not the entire page) from the server every two seconds and alter the status page accordingly.
User clicks a hyperlink element to launch a job on the server.
The CGI receives the parameters from the click and starts the job.
The CGI sends a response of \n
At this point Firefox asks the user if they want to download the CGI script and of course the script is just the \n that the CGI sent. Instead, I want the browser to ignore the response altogether. If my CGI script does not echo a \n apache gives an error. What could I do to tell the browser to ignore the response and stay on the current page? Note that I would rather not reload the current page. I'm thinking there must be some sort of "noop" HTTP response for such a case.
Send back a response with the 204 HTTP status code. From RFC 2616 aka Hypertext Transfer Protocol -- HTTP/1.1:
10.2.5 204 No Content
The server has fulfilled the request
but does not need to return an
entity-body, and might want to return
updated metainformation. The response
MAY include new or updated
metainformation in the form of
entity-headers, which if present
SHOULD be associated with the
requested variant.
If the client is a user agent, it
SHOULD NOT change its document view
from that which caused the request to
be sent. This response is primarily
intended to allow input for actions to
take place without causing a change to
the user agent's active document view,
although any new or updated
metainformation SHOULD be applied to
the document currently in the user
agent's active view.
The 204 response MUST NOT include a
message-body, and thus is always
terminated by the first empty line
after the header fields.
Instead of trying to solve this problem on the server side, you might want to investigate a client side solution. For example, using jQuery you can easily initiate an AJAX asynchronous request to the server on a button click. You don't have to load a new page on the browser at all.
Instead of having the hyperlink be a real <a> or <form> with default behavior, have it be some clickable element whose clicks are handled by your client-side code. The Javascript code should send the job requests with XMLHttpRequest objects, putting it in complete control of how the response is handled.

Categories

Resources