Detect ajax submit - c#

I need to run a specific javascript function only when the page is submitted using ajax.
I've tried the following:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
But it seems to run during normal post-backs as well. I've also tried replacing the Page object with the UpdatePanel control but without any difference.
Is it perhaps possible inside the javascript function MyFunction() to detect if it is an ajax or normal submit?

You can utilize Sys.WebForm.PageRequestManager two events
1) add_initializeRequest --> When an ajax post back is initiated
2) add_endRequest --> when an ajax post back is finished.
PageRequestManager also provides a function "get_isInAsyncPostBack()" which tells that if page is still in process of an existing ajax postback.
Example:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Only one async request at a time
if (prm.get_isInAsyncPostBack()) {
prm.abortPostBack();
}
//Call the function or process you want to perform on ajax request begin
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
//Call the fucntion or process you want to perform on ajax request end
});
Any question, feel free to ask

This code solved the problem. Thanks to #user1341446 for pointing me in the right direction.
Register the javascript function on submit:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
Inside the function detect if ajax submit:
function MyFunction()
{
var isAjaxSubmit = false;
if (typeof (Sys) != "undefined")
isAjaxSubmit =
Sys.WebForms.PageRequestManager.getInstance()._postBackSettings.async;
}

Related

Check is aspx session expired via jquery ajax request

I use asp.net to manage the session state of my site. I also use jquery and $.ajax(...) for synchronous and asynchronous requests.
Normally, in asp.net if a users session times out, it can be detected via a full or partial post-back. However, suppose a partial or full-post-back does not occur because I am using jquery ajax calls to a static c# web method. Whats the best what to know if the session timeout?
i would create a javascript interval to make a ajax request from time to time, something like this:
<script>
$(document).ready(function () {
setInterval(function (){
$.ajax({
url: 'WebMethodhere',
type: 'GET',
success: function (result) {
if(result!='true')
{
//It means that the Session expired, so do somethig
}
}
})
},3000);
});
</script>
I used 3000ms in this example, but the time it's up to you.
And your webmethod could be really simple:
if(Session["WhateverSession"]==null)
{
return false;
}
else
{
return true;
}
There are couple of approaches to achieve it.
Approach #1: Create a generic handler and implement the IReadOnlySessionStateinterface to access session variables from this handler. Use a ajax get request and access this generic handler which provides whether session is active or not.
Approach #2: Decorate a public method of your page with [WebMethod] (using System.Web.Services) and access this method through ajax get request which provides whether session is active or not.
But all these approaches should be used just to check session is active or expired. But if the session is active, it'll renew your session - it may not be desirable. Please check that option also.
The easiest solution was to force a post back at certain intervals.
<meta http-equiv="refresh" content="1800">

Button Not Working Without Refreshing Page

I am building a website with some simple functions and I'm running into some issues. I can't provided any sample code because I have no idea where the problem lies and technically the site is not crashing.
The frontend of the site is html and javascript, the backend I'm using ASP.Net and C#.
There's a button on the page, which will trigger a function in javascript. The function will then make a call to the backend aspx file (say, myFunction.aspx) and generate a output file for the user to download.
Everything is working just fine. I was getting the expected result and was able to download the output file with no problem.
I didn't notice the issue until I try to re-run this function.
I hit the button again but it wasn't doing anything (I was also using Httpfox so I know it's not calling anything)
I realize that I wasn't able to run the function again without refreshing the page. After refreshing the page it works just fine.
Can anyone explain why its this way? How can I go about debugging this issue? I don't even know if the problem is with the fontend or the backend.
Thanks for the help.
EDIT
This is how I created the button.
<button dojoType="dijit.form.Button" type="button" onclick ="myJSFunction('uploadForm')">Generate</button>
and this is how the function is calling the asp backend
var myJSFunction= function (formId) {
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
EDIT 2
I just notice something interesting.
I have been running in Firefox using HttpFox and was not getting any error message. Then I tried to run it in Chrome using F12 and I'm getting red alerts.
In Chrome, under the Network tab, the status says "canceled", but I was still getting the output.
How could this happen? How can I find where the issue is?
Check your javascript console to see that you don't have any errors on the page. Otherwise post your asp.net markup for the button and the javascript function.
Edit:
Try returning false from your javascript function. This will prevent the default browser behavior from executing (What's the effect of adding 'return false' to a click event listener?)
A workaround might be to unnbind and then rebind the click event on your element so every click is effectively the "first", to avoid anything that dojo or something else may be doing out of your control. I don't know dojo, but based on http://dojotoolkit.org/reference-guide/1.9/dojo/on.html#dojo-on the following should be about right:
var updateHandle;
var myJSFunction= function (formId) {
updateHandle.remove();
dojo.io.iframe.send
({
url: 'myURL/myFunction.aspx?parameter=p',
form: dojo.byId(formId),
method: "POST",
handleAs: "text",
load: function (response, ioArgs) {
dojo.byId("timeStamp").value = response;
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction(formId);
});
}
error: function (response, ioArgs) {
alert("Failure:" + response);
}
});
}
updateHandle = on(your.buttonElement, "click", function(){
myJSFunction("myFormId");
});
Thank you all for the help and suggestion.
I have found the solution to the issue. All I need is a single line to the frontend code.
dojo.io.iframe._currentDfd = null; //add this line
dojo.io.iframe.send
({...
});
Thanks for the help.

Redirect a page inside a async method

Requirement:
User calls a page and I display page is loading while i execute a method in background and redirect to the url that the method returns.
Tried using async method call in pageload ,pagenotredirected as already loaded.
Tried updating textbox from the async method and call textboxonchange not working as page aleady loaded
Have added the code for ajax per ur suggestion please review
I call a async method inside pageload and in the pageload I display loading message ,after the async methos completes I get a url ,iam trying to redirect to that url but iam unable to do it inside the async as the page is already loaded ,so iam updating an hidden textbox with this url and using the onchange event in that text box and redirecting but still the page is not redirected,can someone please suggest a better way to do this-Thanks
<asp:TextBox runat="server" ID="urlTextBox" Value="" Style="display:none;" AutoPostBack="true" ></asp:TextBox>
$(document).ready(function () {
$('#urlTextBox').change(function () {
var keyword = $("#urlTextBox").val();
if (keyword.length > 0) {
window.location.href = keyword;
}
});
urlTextBox.Text = url;
the urltextbox gets value inside the async method as I process a long running process inside the async to get this url
I have added a js file in which I call the c# method like this
$(document).ready(function () {
$('#outputFromCmdLine').Text = "Loading...";
GetOutputFromCommandLine();
});
function GetOutputFromCommandLine() {
$.ajax({
type: "POST",
url: "Page.aspx/ConvertToBatch", //url to point your webmethod
contentType: "application/json; charset=utf-8",
dataType: "json",
async:true,
success: function (Result) {
window.location.href = Result;
},
error: function (request, status, error) {
alert(request.responseText);
}
});
and the c# method is sync method and returns the url like this
[System.Web.Services.WebMethod()]
public static string ConvertToBatch()
{
some process
return urlstring;
}
I also added the js file name in top of aspx page ,but nothing gets called ,is this the right way to do it
<script type="text/javascript" src="/Scripts/jqueryFile.js"></script>
Instead of calling the async method from inside the page load you should call it using AJAX in JavaScript once the page is loaded. Then you can use the response from the AJAX request to retrieve the URL with which to trigger navigation to.
<script>
$(function()
{
$.ajax(
{
url: "/api/request",
}).done(function(responseUrl)
{
window.location.href = responseUrl;
});
});
</script>
This will wait for the page to be loaded, make some request to the server, and navigate to the response string (expecting the HTTP response body to be a URL).
I think you would use an ASMX web service or better yet an ASP.NET Web API controller to handle the actual request/response.
I know that with Visual Studio 2013 you can create an ASP.NET Web Forms project which includes Web API and configures them automatically to work together. If you are working with an existing project you could add Web API as a NuGet package and add the appropriate plumbing to make it work manually by simply looking at the VS2013 wizard-generated project as an example of how it is done.
EDIT:
It seems you found another way to handle AJAX calls which is using a WebMethod. WebMethods are described in this question.

Timer with javascript and C#

I need to create a timer in an ASP.NET web page.
I have tested some JavaScript code like:
window.onload = function WindowLoad(event) {
setTimeout(function () { alert("DoIT") }, 60000);
}
and it works like expected but when I replace the alert with a call to a C# function like:
window.onload = function WindowLoad(event) {
setTimeout(function () { <% doIt(); %> }, 60000);
}
the function works on the load of the page and not after the specified period.
<% doIt() %> runs during the server side process, not on client. If you want to do something on the server side you should create a webmethod and make a post to it.
Try this blog post, this should be what you are looking for: http://deebujacob.blogspot.com/2012/01/aspnet-ajax-web-method-call-using.html
It's like other people sad you can not call server side functions directly from javascript you have to make a request, that's is way good God gave as ajax :)

Problem with ASP.NET asynchronous calls, waiting for handler to return

I'm trying to find an answer for a problem my developers are having. I don't know this well enough myself...
We are using ASP.NET with C#.
When a user presses a button on a page, we call a hander to save the session variables to the current view state of the form (some IDs that are used).
Then, we call a GreyBox window with other functionality.
Because this is asynchronous, greybox doesn't wait for the handler to respond.
In many cases the greybox is loaded before the session variables are saved to the view state, and in this case, grey box doesn't have the IDs that are necessary.
On the localhost, it is fast enough that we never realized the problem. In production, it is a problem.
What would be the correct solution here?
The asynchronous call to the server to save the session will return a response to the client. Don't start greybox until you have a successful reply from the server. If there is only one thing causing async postbacks on your form, then you can plug into the reply by doing this:
<script type="text/javascript">
//<![CDATA[
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(endRequest);
function endRequest(sender, e) {
// Do stuff
}
//]]>
</script>
For more complicated scenarios see the article on MSDN on this subject.
You need to make sure that you're additional code is running in a callback method from your AJAX request.
If you're manually calling a web service or page method the Sys.Net.WebServiceProxy.invoke method takes a callback: http://msdn.microsoft.com/en-au/library/bb383814.aspx
I have a feeling that the PageRequestManager which David suggested only works if you are using an UpdatePanel to perform the AJAX request.

Categories