Timing Issue with AJAX,ASHX, and webform - javascript

I have an ASP.NET application and I think I am running into a timing issue. I have a control on a webform that will call some Javascript on the OnClientClick and also call code behind via server-side onClick.
I click the button (a print button in my instance) and I call Javascript prompt to enter a reason for the print. I enter whatever and then in the JS I call an ashx (handler) page via AJAX passing the results of the prompt.
The handler then places the Text from the prompt into a session variable. Once the JS is done the OnClick code behind is called calling a method that will grab the reason from the session variable (after the ashx has written it) and log the info and print.
What I am seeing is the very first time I do this I get an error my reason not found (ie. session variable is null). It works every time after that. So, what I believe is happening is the first time the ASHX page is being called, it is being compiled/loaded and not adding info to the session fast enough.
My question is there a clean way to slow down my print function and give the JS call time to complete?

I would remove the serverside onClick and have the onClientClick function post the user's input to where your serverside onClick was going before. Removing the ashx step completely.
If you need the ashx step then I would post the user to the next step in the onComplete event of the ashx ajax call. This will ensure that everything fires in the correct order.

Related

VB.NET calls Javascript function. How do I get javascript function to complete before VB.NET completes?

In a web application I am using a button_Click method in VB.Net to occur when a button is clicked.
I have the following line at the top of my VB.NET method:
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "myFunction", "myFunction();", True)
I want that script to finish before my VB.NET script carries on. Basically, I have validation in my javascript that I want to complete before the VB.NET takes the "validated" data and inserts it into a database.
This betrays a misunderstanding of how web forms work. Here's what really happens:
A user requests your page from their browser for the first time
Your web server runs the ASP.Net page life cycle in order to send an html response
The web server destroys the page class instance it used to complete the request.
The response from the server arrives and is rendered by the user's browser.
The user clicks your button, resulting in a new http request.
The browser destroys the existing html DOM.
The request arrives at the web server, which then runs the full ASP.Net life cycle again, including the Page_Load method.
This time the data included with the request indicates to ASP.Net that it should also run your button's Click code.
The button registers the javascript to run when the page loads in the browser.
The page lifecycle completes, and ASP.Net sends it's HTML response back to the browser.
ASP.Net destroys the page class instance again.
The response arrives at the browser, which renders it from scratch by creating a whole new html DOM.
The page's javascript load event fires, and some javascript included with ASP.Net pages kicks off the javascript startup script registered by the button.
I need to point out some things about this process, namely that order between steps 3 and 4, steps 6 and 7, and steps 11 and 12 are accurate. When there is working page visible in the browser, the server has already moved on and destroyed anything used to create that page (except Session variables). While VB.Net code is running, the browser doesn't even have a page to show yet.
What you should learn from this is that at time the javascript runs, not only has the VB.Net method already finished, but the entire page class was already destroyed. There's an idea of continuity here for both the browser's web page and the VB.Net Page class instance that just doesn't happen. It's just nice that all this happens in a way that is mainly transparent to the user.
Fortunately, there are some things you can do to avoid this full process. You might look into using an UpdatePanel for part of your page, changing the button to trigger a WebMethod, or translating more of the VB.Net code into javascript in the first place. However, all of these will likely require significant re-thinking of how your page is going to work. In this case, you might find and a Validation control best fits your needs.
This is assuming that myFunction is a javascript function existing on your client side. It will call myFunction on the client side.
<asp:Button ID="btntest" runat="server" Text="Add Record"/>
<asp:CustomValidator ID="myCustomValidator" runat="server" ControlToValidate="someControl" ErrorMessage="Validation Error" ClientValidationFunction="myFunction"></asp:CustomValidator>
This is assuming that you javascript is doing some validation as well. It would look something like this. If args.IsValid = false, then the validator won't allow a postback and the vb.net code won't execute. This is the point of a validator.
function myFunction(sender, args) {
var someControl = document.getElementById(sender.controltovalidate).control;
//Let's assume someControl is a textbox and we don't want it bigger than 10
if (someControl.value > 10) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
Hopefully, this gets you going. Let me know if something isn't working right and you need more help.

Call JS function before redirect

The situation is as follows:
A user on the client side enters some data and presses a command button that initiates an ajax request. Depending on the input data the JSF Bean on the server side redirects to different pages. But in addition the HTML5 features localstorage respectively sessionstorage should be updated on client side, also depending on the results from the bean. For the storage some data entered from the user is necessary, so that the java script for the storage has to be within the original page.
Now, the problem seems to be that after the response the redirect is always done first, before executing the js function and so it is not possible to access the input data from the user on the client side of curse.
I tried things for calling the js function after pressing the command button like "oncomplete" on the client side using callback parameters (redirect takes place earlier) or RequestContext.execute from the server side (but this internally also uses the oncomplete event i think).
One possible solution I could imagine is to use window.onunload on client side and a hidden input formular to get the result of the bean. But isn't there a better solution?
You need to redirect by JS instead of by JSF. Return null from action method so that it returns to the same page and then execute the following script to perform a redirect in JS.
window.location = newURL;
If you use PrimeFaces with JSF then it's possible to make global override of PrimeFaces.ajax.ResponseProcessor.doRedirect in javascript to put any custom code before actual redirect happens:
PrimeFaces.ajax.ResponseProcessor.doRedirect = function(node) {
// <<<< your code is here >>>>
window.location = node.getAttribute('url');
}
Put this code in some js file and include it in all your pages.

Is there any way to call JavaScript function from a perl script?

I am trying to write a Perl script that will take a user parameter from command line and with his parameter, Perl script will call a JavaScript function in a HTML page. How can I go ahead to with this?
Not that I've seen. Perl is strictly server side, and JS functions you're talking about are on the client.
The closest you would get is have the Perl script write a block into the HTML page so that the page fires it on load to perform the action. But that's a little shaky at best to do.
It depends on whether the browser or server will be taking the first step.
If the server needs to run code first and then execute some JS, then #skyburner's solution would work. Essentially you would already have some functions defined on the page, but then you would dynamically add a block of JS to call whichever function you need to.
However, if the Perl is being run due to a user's action on the current page (such as clicking something or submitting a form), then AJAX would be the way to go. You would use JS to submit an HTTP request to the Perl script. The Perl would then return some value back to the JavaScript and execute some function based on this result. This would all happen "behind-the-scenes" without the user leaving the page.
If I understand correctly about what you want, since not all the browsers support socket, this is what you can do:
Have an ajax service call periodically sending requests to the server for update
Once the the parameters from the command line are taken, you can send the result along with an ajax response back to the page, and call the function in the ajax request callback function.
Also, another option, you can use reverse ajax to accomplish this. See Wikipedia about reverse ajax (comet), especially Ajax with long polling.

jQuery.post callback not executing

When I make a call with jQuery.post, the callback is not being executed, but only if the call is made in a js file loaded into the webpage. If I copy and paste the same call into the javascript console of the browser, the callback get's executed. I know that the function is being called, because if I replace the call to jQuery.post with a simple alert(), it shows up. I've made sure the post request is completing (data is inserted into db on server side). I've also made sure that it is returning with a 200 code.
Also, this function is being called on demand when I click a button, so the DOM should be fully loaded by then.
Why would this be executed properly from the console, but not from a js file?
The problem ended up being that I wasn't returning false from the onclick callback, and so the page was refreshing every time I submitted the form. The refresh happened so fast that I didn't notice. If I moved the submit button out of the form, or returned false from the onclick callback, the expected behaviour occurred.

ASP.NET: Call codebehind if javascript doesnt exist in browser,Else javascript function

In asp.net page, How can i call the javascript methods for form processing-submitting if the user browser supports javascript and use code behind events if the browser does not support javascript.I have the javascript code to send the form data to an ajax server page using jquery. Don't know how to invoke the needed one based on the browsers javascript availability
Create the form that does a postback and submits the data without JavaScript then set the click event on the submit button to call your javascript function.
Then use e.peventDefault() and e.stopPropagation() in the click event to prevent postback.
You may also need to capture the enter key press event and prevent it from causing a post back as well.

Categories