I have a jquery ajax call to a c# asmx web method, which does some processing,and internally calls more api's \ DB operation ,etc etc taking approx 20-30 seconds
WEB METHOD
[WebMethod]
public void dummy()
{
File.Create(#"C:\test\test" + DateTime.Now.Millisecond.ToString() + ".txt");
System.Threading.Thread.Sleep(60000);
}
AJAX CALL
$.ajax(
{
url:Service.asmx/dummy",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (strData) {
alert('done');
}
});
The ajax call is within a loop which is fired 2 times, but the web method gets called only Once, so i tried async: false, then web method gets hit twice but after the 60 seconds delay.
What am i doing wrong ?
Remove the delay by System.Threading.Thread.Sleep(60000) in code behind and send the second ajax call after receiving the response from the server side.
$.ajax(
{
url:Service.asmx/dummy",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (strData) {
alert('done');
//send second call here
}
error: function (jqXHR, textStatus, errorThrown) {
//send second call here if required.
}
});
If you do not have any synchronization problem for simultaneous call then you can remove delay and send multiple call simultaneouly.
Related
i have some problem when i use jquery.when function in web form using master page
This is my code in web form using master page
$(document).ready(function(){
$.when(masterPageFunction()).done(function(){
webFormFunction();
});
})
And this my master page
function masterPageFunction() {
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
}
})
}
})
}
result is web function is running when master page function not done
please help, thank you so much
You're close, but the when, then and done functions rely on promises. You aren't returning any promises in your code, so it's just running straight through.
First, you'll need to obtain the result of the promise after it completes in the done function in your master page. We'll do that by adding a response parameter to the callback, then passing it through to webFormFunction.
$(document).ready(function(){
$.when(masterPageFunction()).done(function(response){
webFormFunction(response);
});
})
Next, we need to add a promise to masterPageFunction and return it. You resolve the promise with the response you want to send back to the done function in your master page. Like so:
function masterPageFunction() {
// Create the promise
var deferred = $.Deferred();
//In this function i call 2 ajax like this
$.ajax({
type: "POST",
url: "/api/master/xxx/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$.ajax({
type: "POST",
url: "/api/master/xxx2/",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// Resolve the promise with the response from $.ajax
deferred.resolve(response);
}
});
}
});
// Return the promise (It hasn't been resolved yet!)
return deferred.promise();
}
In this way, webFormFunction won't be called until the second ajax call completes, which resolves the promise.
i want to call the unlock method on closing or redirecting other page, so i have used ajax call. but the method unlock is not firing. please let me know what i am doing
[WebMethod]
public void Unlock()
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
Where you passing project_id in your ajax call???
pass project_id in your method
[WebMethod]
public void Unlock(string project_id)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(Request.QueryString["project_id"]), "");
}
and then rewrite ajax call as
function HandleOnclose() {
$.ajax({
type: "POST",
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
data : "{project_id:'1234'}",
dataType: "json"
});
}
window.onbeforeunload = HandleOnclose;
There's a couple of issues. Firstly your WebMethod expects a querystring parameter, yet you're sending a POST request and you also don't send any data in the request. You should provide project_id as a parameter in an object to the data property of the AJAX request.
Also note that sending an AJAX request in the onbeforeunload event is one of the very few legitimate cases where you need to use async: false to stop the page from being closed before the AJAX request completes. Try this:
[WebMethod]
public void Unlock(string projectId)
{
CreateProject_BL _objcreatebl = new CreateProject_BL();
_objcreatebl.upd_lockedBy(Convert.ToInt32(projectId), "");
}
function HandleOnclose() {
$.ajax({
type: "POST",
async: false, // only due to running the code in onbeforeunload. Never us it otherwise!
url: "ProjectDetails.aspx/Unlock",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { projectId: '1234' }
});
}
window.onbeforeunload = HandleOnclose;
Also note that depending on the browser you may be restricted from sending an AJAX request in the onbeforeunload event at all. See this question for more details.
I make a total of four Ajax calls in my .NET application. Three of them work without a hitch except the last one.
Note: I HAVE to use .aspx for these calls and not mypage.aspx/mymethod because of our architectural constraints.
Ajax call that works:
$.ajax({
type: "POST",
url: "myaddress/GenerateOpinionHTML.aspx",
data: JSON.stringify({ id: featureId, pageNumber: pageNumberIndex }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
SOME PROCESSING (IT WORKS)
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log(err);
}
});
and
[WebMethod]
public static string GenerateOpinionHTML(int id, int pageNumber)
{
// ...
}
Ajax call that does not work:
console.log("SUBMITOPINIONCLICK");
var param = " ";
$.ajax({
type: "POST",
url: "myaddress/SaveOpinion.aspx",
data: JSON.stringify({ parameter: param}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SAVE OPINION SUCCESSFUL");
console.log(msg.d);
CloseLB('GiveOpinionLB');
},
error: function (xhr, status, error) {
var err = xhr.responseText;
console.log("ERROR " + "STATUS: " + status);
}
});
and
[WebMethod]
public static string SaveOpinion(string parameter)
{
// ...
}
The web method SaveOpinion is never called according to the logs. Do you have any ideas or suggestions? I tried adding parameters, without parameters, checking my web.config file (though I shouldn't have since the other calls work)...
The error I get on the browser console is a "parseerror". I'm certain I wouldn't be getting an error if the method was called.
I think your URL should be like
url: "Your FolderName/PageName/Function Name",
Like
url: "myaddress/SaveOpinion.aspx/SaveOpinion"
but in your code this is different so that please check.
Have you checked if method SaveOption return something to the client?
If you specify dataType as json, you should return (at least): {}
Ok so we "solved" it. We just found a very dirty band-aid workaround that works.
We made a custom handler (.ashx) that we defined in our architecture as a SaveOpinion.aspx page.
We then called this custom handler page with jQuery and voilĂ it works, we had to obviously pass all necessary parameters manually, ie. fetching all values from textBoxes etc with jQuery and not from the context as we did before.
Since this is run in some sort of thread (I don't really know the details) we had to configure it so that it simulates the same user authentification.
Anyway I hope this provides some measure of guidance for those with this kind of obscure problems.
I'm writing a client for an asp.net handler that processes and sends notifications to the polling clients. I make ajax calls with jquery every 10 seconds waiting for the notifications. The problem is every time I send a response back to the client it always calls the error callback. With fiddler I see the json response arriving to the client with status 200 but in firebug the request keeps waiting.
Client:
function poll(){
$.ajax({
url: "http://localhost:53914/NotificationChecker.ashx",
data: { userName: "ggyimesi" },
type: 'POST',
success: function(data){
alert("asd");
$('div#mydiv').text(data.Text);
},
complete: poll,
error: function(data){alert(data.status);},
timeout: 15000 });
}
$(document).ready(function(){
poll();}
);
Server:
Response response = new Response();
response.Text = this.MessageText;
response.User = Result.AsyncState.ToString();
string json = JsonHelper.JsonSerializer<Response>(response);
Result.Context.Response.ContentType = "application/json";
Result.Context.Response.Write(json);
I actually found the problem. The problem was that I started the client html from my local machine not hosted on the web server and that caused the problem. After adding it to the local web server the original code worked as it is.
I think your ajax call is missing the following:
dataType: 'json',
contentType: "application/json; charset=uft-8",
Try this:
$.ajax({
url: "/NotificationChecker.ashx",
dataType: 'json',
contentType: "application/json; charset=uft-8",
data: { userName: "ggyimesi" },
type: 'POST',
success: function(data){
alert("asd");
$('div#mydiv').text(data.Text);
},
complete: poll,
error: function(data){alert(data.status);},
timeout: 15000 });
}
I think your problem is that you pass your username like this
data: { userName: "ggyimesi" }
I think you should do it like this
data: '{userName:"' + ggyimesi + '"}'
and you can add more like this
type: "POST",
url: "NotificationChecker.ashx",
contentType: "application/json; charset=utf-8",
dataType: 'json',
I am trying to build an asp.net(c#) page that updates some state texts every second.
Now I have implemented an button that calls another PageMethod which restarts something and takes a little while. The problem is, that when I call the restart PageMethod , the update PageMethod can't update as long as the restart method is proceeding...
I wrote a little example to show what I mean:
WebMethods in my Page:
[WebMethod]
public static string Update()
{
//return "a" to see when the Update PageMethod succeeded
return "a";
}
[WebMethod]
public static string Restart()
{
//the restart will take a while
Thread.Sleep(2000);
//return "a" to see when the Restart PageMethod succeeded
return "a";
}
the html elements to update:
<p id="update" style="float:left;"></p>
<p id="restart" style="float:right;"></p>
the Pagemethod calls:
callUpdate()
function callUpdate() {
PageMethods.Update(function (text) {
//itself+text from pagemethod
$('#update').text($('#update').text() + text);
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
PageMethods.Restart(function (text) {
//itself+text from pagemethod
$('#restart').text($('#restart').text() + text);
});
setTimeout(callRestart, 1000);
}
Note: The Update is also called every second after it finished, just to see how it works
To clarify: I want the PageMethods to execute independent to that the other PageMethod has finished.
I also flew over some links like:
http://esskar.wordpress.com/2009/06/30/implementing-iasyncresult-aka-namedpipeclientstream-beginconnect/
http://msdn.microsoft.com/en-us/library/aa480516.aspx
But I don't think this is what I need (?)
And I really don't know how to call that from Javascript (BeginXXX and Endxxx)
*EDIT: *
Regarding to Massimiliano Peluso, the js code would look like this:
callUpdate()
function callUpdate() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Update",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#update').text($('#update').text() + msg.d);
}
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Restart",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#restart').text($('#restart').text() + msg.d);
}
});
setTimeout(callRestart, 1000);
}
Note: when I run the Page with the new js, there is exactly the same problem as before: The Update method can do nothing until the Restart method is finished.
you should call the page methods using an Async call instead.
have a look at the below. It is a generic way to call a page method using JQuery
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
you should use this code to replace the page method calls
PageMethods.Restart(function (text))
PageMethods.Update(function (text))
It's because an Request only Proceeds when no other Request is processing.
Thats because two Processes can't acess to the same SessionState (Sessionstate is not Threadsafe).
So to achieve that Requests are processed at the same time, you have to set EnableSessionState in the #Page directive to either 'ReadOnly' or 'false'