I am using an authentication cookie passed between websites on the same domain. The cookie contains some user info and page info (the accession number). The design goal is for the user to click a button on the referring website, and it will launch a second website, authenticate based on the cookie, and do some useful stuff with the accession number. I got most of this built, including getting the authentication passed and properly parsed out on the receiving system.
The problem I am having is that I can't get the data within the cookie into the javascript on the page. It seems when i launch website2 from website1, $(document).ready() is not fired after the page_load event (which handles the cookie parsing). Also I tried using a literal to post the javascript code, it's never fired (seemingly it places it after the client side stuff is executed.
What I really want to do is call a javascript function getResults(accnum) using this data.
I have this code on the page_load event:
if (userdata != null)
{
accnum = userdata[4];
}
if (accnum != String.Empty)
{
//HttpCookie accnumcookie = new HttpCookie("accnum", accnum);
//this.Context.Response.Cookies.Set(accnumcookie);
}
}
When I run the .Set function, I'm not really sure of the innards and details, but long story short, the cookie is set but does nothing.
This is the document.ready.
$(document).ready(function () {
var accnum = new String();
accnum = GetCookie('accnum');
if (accnum != null) {
document.cookie = 'test=testz';
var srch = document.getElementById('crit');
srch.style.display = 'none';
getResults('', 'accnum', accnum);
}
Related
In my ASP.NET page my users can check the customer balance before sending any payment. Balance update label is inside the Update Panel and sometimes it takes longer than usual to check the customer balance, so users might want to just cancel the checking and proceed to next step.
Is there any way to stop the current Update Panel event (while it's running and taking too long) and call some button Click event by using JavaScript?
You can use code like this to cancel the refresh of the UpdatePanel.
var divElem = 'AlertDiv';
var messageElem = 'AlertMessage';
Sys.Application.add_load(ApplicationLoadHandler)
function ApplicationLoadHandler(sender, args)
{
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(CheckStatus);
}
function CheckStatus(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelRefresh') {
prm.abortPostBack();
}
else if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'RefreshButton') {
args.set_cancel(true);
ActivateAlertDiv('visible', 'Still working on previous request.');
}
else if (!prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'RefreshButton') {
ActivateAlertDiv('visible', 'Retrieving headlines.');
}
}
function ActivateAlertDiv(visString, msg)
{
var adiv = $get(divElem);
var aspan = $get(messageElem);
adiv.style.visibility = visString;
aspan.innerHTML = msg;
}
if(typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
However, the processing of the ASP.NET request will continue in the background.
If the user cannot navigate until this is complete, it could be the ASP.NET session locking stopping your second request from starting until the first one is complete. You could try checking the Response.IsClientConnected property in the code of your first request and abort it if false. You may need to check this in a separate thread if your main thread is busy doing the processing, but it depends on the architecture of your application.
A simpler suggestion is to try disabling session, or setting it to read only if your page does not make use of it or write to it (quoted from this answer):
If your page does not modify any session variables, you can opt out of most of this lock.
<% #Page EnableSessionState="ReadOnly" %>
If your page does not read any session variables, you can opt out of this lock entirely, for that page.
<% #Page EnableSessionState="False" %>
If none of your pages use session variables, just turn off session state in the web.config
<sessionState mode="Off" />
I found a solution in C#. This code is put inside the code that updates the UpdatePanel control:
Thread th = new Thread(DoSomething);
th.Start();
if (!th.Join(TimeSpan.FromSeconds(3)))
{
th.Abort();
}
If the UpdatePanel takes longer than 3 secs to update then it just aborts the current thread.
I have a WCF service locally in my ASP.Net 4.0 application. I have the following in my MasterPage:
<asp:ScriptManager runat="server">
<Services>
<asp:ServiceReference Path="~/Services/AJAXDataService.svc" />
</Services>
</asp:ScriptManager>
Then on my page I have the following JavaScript code:
...
5 calls to the service to fill in drop downs and such
...
$(document).ajaxStop(function () {
var service = new BOR.AJAXDataService();
service.GetComplaintDetails(passed, FillComplaint, DefaultFailure, null);
}); // AjaxStop - Event - Everything is done, now load the Model
This happens in the Document Ready event after about 5 other ajax calls. If I do NOT put this in the ajaxStop event, it works, but depending on database and network latency, it may not work because the GetComplaintDetails needs what comes back from each of the previous calls.
I found the ajaxStop method and thought it is exactly what I need. But apparently the Microsoft/ScriptManager calls do not go through jQuery (of course) so that function is pointless.
Q: Is there a way to intercept the being/end, start/stop events of each of the previous calls when using the ScriptManager reference? I would rather do this than creating the long and wordy jQuery calls.
Okay, looking into it further I came up with a decent work-around. It uses the ASP.Net Client Side Framework (Sys) to make it work.
I created a global variable:
var _ajaxCounter = 0;
I put the following code in my global/MasterPage Document Ready method.
if (Sys.Net.WebRequestManager != undefined) {
Sys.Net.WebRequestManager.add_invokingRequest(WRMInvoke);
Sys.Net.WebRequestManager.add_completedRequest(WRMCompleted);
} // if we have the Sys.Net namespace
Then in that .js file that gets loaded on every page, I have the two methods:
function WRMInvoke(sender, args) { _ajaxCounter++; }
function WRMCompleted(sender, args) {
_ajaxCounter--;
if ((_ajaxCounter == 0) && (typeof (SomeFinalMethod) != "undefined")) {
Status_Saving(false);
Status_Working(false);
SomeFinalMethod();
}
}
So now on a page where I need to make sure something happens AFTER everything else, I just have to define a SomeFinalMethod method like the following:
function SomeFinalMethod () {
var passed = $("#hdnComplaintID").val();
if (passed != "") {
var service = new BOR.AJAXDataService();
service.GetComplaintDetails(passed, FillComplaint, DefaultFailure, null);
}
SomeFinalMethod = undefined;
}
Note the last line of the SomeFinalMethod, it wipes itself out. In some cases, this is unnecessary. However, on my page, there are things the user can do that perhaps trigger other ajax calls and the last one would call this method again and create a loop.
For reference, check out this MSDN article.
Hope it helps others out there.
In my Phonegap Android app, I have the following Javascript code:
function onDeviceready()
{
window.plugins.webintent.getUri(function(url)
{
alert("WebIntent Fired Up! URL is " + url);
if (url.substring(0, 37) === "https://xxxxxxx.com/confirmation.html")
{
alert("intent matched!");
var params = url.substr(url.indexOf("?") + 1);
params = params.split("&");
var verificationData = params[0].split("=");
var emailData = params[1].split("=");
launchLinkEmail = emailData[1];
launchLinkVerification = verificationData[1];
alert("verification is " + launchLinkVerification);
alert("email is " + launchLinkEmail);
}
});
}
$(document).ready(function() {
document.addEventListener('deviceready', onDeviceready, true);
});
The problem is that the variables launchLinkVerification and launchLinkEmail seem to get set after the page is loaded and the Javascript is finishing up, and so their value is empty when I try to call it anywhere that I want to use them. The alerts always display the information I want, but if I try to display them anywhere in my HTML pages, or set conditionals based on their value, neither work.
On the other hand, it seems that if I use window.plugins.webintent.getUri(function(url) anywhere other than onDeviceready it sometimes doesn't execute at all (or at least not under conditions that I can predict or understand), and again the variables don't get set.
Ultmately, what I want to do is:
Get the data from the URL that WebIntent captures.
If the data from WebIntent matches certain criteria, then switch to another page using window.location = confirmation.html
Fill two fields on the form on confirmation.html with the two variables I got from the URL that WebIntent picked up.
How do I get the data from the Webintent call, switch pages depending on what that data is, and then use that data on the new page?
I haven't used the WebIntent plugin specifically, but if I understand your description correctly, I think you're running into a problem where you're running some JavaScript in the head or maybe in the body to configure the page the way you want it. But that code is dependent upon what happens in your onDeviceready(). The call to onDeviceready() is going to be made asynchronously at anytime PhoneGap feels it is ready. Usually it is called quickly, but quickly is a relative term.
What you likely need is someway for this async code to then trigger the code you want. JQuery provides the $.Deferred() object which you might find helpful. You can setup a Deferred, you add your other code in with Deferred.done(), and when it runs onDeviceready() resolves the object which then runs the callbacks.
http://api.jquery.com/jQuery.Deferred/
I've used this to allow something like onDeviceready() to trigger a series of other behaviors in my application which I may not have wanted to structure into one big function.
I need to use JavaScript (jQuery if applicable) to trigger my modal call if the result of my function is true and the referring URL is not of the domain.
The desire is that the user visits the main splash page and as long as they have not been redirected there by the site itself (via timeout on a session, invalid login credentials, etc) it displays the message so:
function showModalIf() {
if (checkFunction) {
if(////// REFERRING URL not from this site)
Trigger Modal Call
else
Don't Do anything else
}
}
Assuming you use jQuery UI Dialog to show the modal
function checkReferrerExternal() {
if (!document.referrer || document.referrer == '') return false;
var regex = /^https?:\/\/\/?([^?:\/\s]+).*/;
var referrermatch = regex.exec(document.referrer);
var locationmatch = regex.exec(document.location);
return referrermatch[1] != locationmatch[1];
}
function showModalIf() {
if (checkReferrerExternal()) {
//show jQuery UI Dialog modal or replace with whatever
$("div#dialog").dialog('open');
}
}
Check demo page http://jsbin.com/efico
If you are talking about forced redirection in the code, and not just a hyperlink click from elsewhere in the site, you could add a query string parameter on your redirection and check that way. Another option is to set a cookie and check for the cookie in javascript.
Here is a nice link on cookie handling in Javascript:
Javascript - Cookies
And here's one for parsing query string params/hashes in Javascript as well:
Parsing The Querystring with Javascript
Hope this points you in the right direction :)
I have a page with a dropdown. The onchange event calls a Javascript function (below) that includes an Ajax block that retrieves data and populates a TEXTAREA. On the surface, everything works.
I can select any item in the list with no problems. However, if I select an item that has previously been selected, the Ajax call appears to hang. It looks like maybe some weird caching issue or something. If I close the browser and reload the page, all items work again until I re-select.
I've tested for the readyState and status properties when it's hanging, but I get nothing. Am I missing something?
The page is a client project behind authentication so I can't post a URL, but here's the Ajax code. This is in a PHP page, but there's no PHP script related to this.
function getText( id ) {
var txt = document.getElementById( "MyText" );
txt.disabled = "disabled";
txt.innerText = "";
txt.className = "busy";
var oRequest = zXmlHttp.createRequest();
oRequest.open( "get", "get_text.php?id=" + id, true );
oRequest.send( null );
oRequest.onreadystatechange = function() {
if( oRequest.readyState == 4 ) {
if( oRequest.status == 200 ) {
txt.innerText = oRequest.responseText;
} else {
txt.innerText = oRequest.status + ": " + oRequest.statusText;
}
txt.disabled = "";
txt.className = "";
oRequest = null;
}
}}
Edit: The code block seems a little quirky; it won't let me include the final } unless it's on the same line as the previous.
You're setting the onreadystatechange function after you're sending the request. If it takes a long time (ie if it goes to the server), this will probably work, since there will be a delay before it tries to call the callback.
If the page is cached, though, the browser is probably trying to call onreadystatechange immediately in the send method. Move your assignment to onreadystatechange to before the open/send code.
HI,
The caching is due to the same url thats being called repeatedly. If you change the URl dynamically then this issue can be rsolved. Something like by adding a querystring with the current time with the request ( or any random renerated number ) you can change the url without affecting the result
I would guess that you are running into a caching issue. I have noticed that Internet Explorer is more aggressive at caching ajax calls than Firefox is. One way to be sure of what is happening is to use Fiddler2. This application monitors your web traffic, and you would be able to see if the browser is making a request or not, and what cache headers are coming back on the responses that you do get.
You can download fiddler2 from http://www.fiddlertool.com/fiddler/