how to get Asynchronous response to an Ajax request? [duplicate] - c#

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
ASP.NET Server does not process pages asynchronously
There is a question regarding Asynchronous response to an Ajax request.
I’m working on a web application to enable some simple image processing actions for user, using ASP.Net + Ajax. As most of image processing actions takes a while to accomplish, we’d like to utilize user to send the request to the server through Ajax, and get the partial response immediately, while the server is processing and to send completed response in a later time (i.e. 10/20 seconds later for instance).
This way, I suppose the server should be able to push the late response (which obtained 10/20 seconds later) to the client.
Is there any idea how to realize such interaction?

The closest thing you'll get is JSONP, which can be used with jQuery.

like:
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/tags/ravendb/wikis',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
jsonp: 'jsonp'
async: true,
success: function (data) {
if (data.tag_wikis.length > 0) {
alert(data.tag_wikis[0].wiki_excerpt);
}
},
});

Related

Cancel Service Call

I am using a WCF service, it is not an asynchronous service.
I do database operations in them. the Database operations return me huge result.
I want to provide a way to cancel the operation to my client.
Can anyone please suggest to achieve the same. I googled a lot
also could find out some soluions, some are saying to make the service operation as asynchronous.This is what I got from msdn
http://msdn.microsoft.com/en-us/library/ms731177(v=vs.110).aspx
But how do I stop it.
Also as I am new to this, I am not able to figure out the thing.
Can anyone please help me with this.
Thanks in advance.
Regards
You can keep your service synchronous but make async calls inside of your methods, around database queries for example. In this case you can use class Task which supports CancellationToken. But you should be on .NET 4 and up.
I you only want to cancel Service call (There is no session Locking (Session Creation/updation/deletion), you can make ajax call to service in javascript like :
var xhr;
var serviceUrl = "Service1.svc/GetData";
xhr= $.ajax({
type: "POST",
url: serviceUrl,
data: "{\"value\":\"request\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//anything you need to do on success
}
});
For aborting request, you can do :
if(xhr && xhr.readystate != 4){
xhr.abort();
}
Please not that will abort the handler waiting for request & not request itself and if you are playing with Session(except for read), it will not work & wait for request to complete.
If you have above case, its better to use Task as mentioned by vzayko.
Also if you're using MVC 4, you can also use TAP(Task-based Asynchronous Pattern), which is specifically optimised for using tasks in ASP.net MVC.

JSONP no get value result

I'm doing a project for college where one WebSite sends commands to a Windows Forms application. This application is responsible for access to serial port and send and receive commands.
Communication between the Website and the Windows Forms application, I used Web Api, however after publishing, auditioning remembered that the localhost in a C # WebSite. Net's own site and not my Windows Forms application.
I changed the call to the Web Api directly use Ajax and not a controller.
In the examples I found I saw that I use JSONP, but I can not read the results and use it on my website.
The calling code and return seen by Chrome are below
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
jsonpCallback: "cmdTorre",
jsonp: "cmdTorre"
});
}
function cmdTorre(data) {
alert(data);
}
Response Header
Content-Length:10
Content-Type:application/json; charset=utf-8
Date:Tue, 10 Jun 2014 11:18:30 GMT
Server:Microsoft-HTTPAPI/2.0
Response
No Properties
Windows Forms APIController
namespace TCCWindows.Lib
{
public class GPSController : ApiController
{
[HttpGet]
public string Posicao()
{
var coordenada = TCCWindows.FormPrincipal.PegarCoordenadas();
return coordenada.Latitude + "|" + coordenada.Longitude + "|" + coordenada.Altitude;
}
}
}
First, you ajax call looks overly complicated try replacing it with :
function cmdLocal() {
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://local host:8089/api/gps/",
success: cmdTorre,
error: function(err){
alert("You have a error"+err);
}
});
}
function cmdTorre(data) {
alert(data);
}
Please validate the new code carefully. I just typed it in here so can have errors. If this runs at this point you should probably see the error message. That is because your GPSController doesnt seem to be returning a valid JSONP (or JSON for that matter). Please read up on JSONP for more clarification but, I think if you modify your return statement to make it look like following, it should work. Assuming your controller is actually getting called and your network stuff is working:
return "cmdTorre({\"lat\":"+coordenada.Latitude+" , \"lon\":"+coordenada.Longitude+" });"
Basically your return string should look like following when printed on console:
function cmdTorre({
"lat": 23.34,
"lon":34.23,
"alt":50
});
Again I suggest you check the code I wrote for syntax issues as i just typed it up in here, but it should give you the idea.
So problems were:
The return string you are generating is NOT in JSON format
It is also not wrapped in a function call making it a invalid JSONP too.
Lastly my solution should get your code working and JSONP started but its not the right way to do things. Its more of a ugly hack. Your GPS controller should read the HTTP request for parameter called 'callback' which is a accepted convention for JSONP calls. Then instead of hardcoding the function name in the return statement, you should use the value of this callback parameter. Then you dont need to use a specific function like 'cmdTorre' in your jQuery. Instead a anonymus function like success:function(response){...} will work just fine.
Hope that helps.

Update label while a method is running

How do I update a label in a aspx page while a method is running? Perhaps using AJAX (update panel)?
private void button_Click(object sender, EventArgs e)
{
doThings1();
label.Text = "Status1";
doThings2();
label.Text = "Status2";
doThings3();
label.Text = "Done";
}
I want to show step by step. While the method is running when the doThings1() is done, shows "Status1", doThings2() is done, shows "Status2"... In this way, the label doesn't show "Status1" and "Status2", just "Done" when the process is finished. I'd like to show step by step.
This is not an easy thing to do, the way it is in a desktop application. You need to start an asynchronous operation that will continue after the request ends, you'll need to have the client continually poll the server for updates as to the progress, and the server side asynchronous code will need to update some sort of share state (i.e. session, a database, view state, etc.) that the polling method can read the progress from. All around it's quite inefficient (especially if you have a lot of users doing this) and takes some time to write. Here is an example on MSDN that does this, to give you an idea of what's involved.
The rule is: 1 request --> one response.
Different approach:
You can these methods execute with 3 asyncron javascript call and set the labels' text at the success callback.
http://api.jquery.com/jQuery.ajax/
Example:
$.ajax({
type: "POST",
url: "URL.asmx/doThings1",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// result will be "done" from the function of webservice below.
// set the first label text
},
error: function(xmlHttpRequest, status, err) {
alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
}
});
Repeat these calls 3 times and do your modifications in different functions.
You can handle your buttonclick at client side with jquery or pure javascript.
You can use a webservice or generic handler to execute server side methods.
How to create webservice
[WebMethod]
public string doThings1()
{
return "done";
}
It sounds like you want to show the progress of some task that is running on the server. The signalr library will allow you to send real time updates to the client from the server. So anytime the task completed a stage (Status1, Status2, etc) of the task, it would send an update to the listening clients with the new status.
You could also have some javascript request the task status from the server every few seconds and display it to the user.

web request from the user browser

is it possible to send a web request from the user browser to another api and then process the result sent back??
im trying the following ajax code but its not working, i was wondering whether is it possible or not and if its a yes how can i implement it ...
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=xml",
dataType: "xml",
success: function(xml) {
alert("sucess");
$(xml).find('Ip').each(function() {
var ip = $(this).find('Ip').text();
alert(ip);
});
}
});
});
Due to same origin policy restriction you are pretty limited to sending AJAX requests to your own domain only. JSONP is a common workaround but the remote site needs to support it. Another workaround consists in crating a server side script on your domain which will serve as a bridge between your domain and the remote domain and it will simply delegate the AJAX request sent to it from javascript.
Should be possible, I have done the same.
BUT you have to have the pages on the same server, you cannot send a request to another server, in that case you would have to use a proxy on your server to relay the call.
Just to add to what was already said: if you can't create your own JSONP proxy, you can use YQL service which creates that proxy for you. Note that YQL will wrap your data with it's own meta data (unless there is a way yo disable that...).
By the way, you should use JSON output instead of XML output from your API service. JSON is a more lightweight format and as such is more adapted for Web.
Below is a fully functional example with your API URL (outputting JSON this time) and YQL:
var apiRequestUrl = "http://api.ipinfodb.com/v2/ip_query.php?key=a9a2b0ec2c4724dd95286761777b09f1c8e82894de277a5b9d7175fa5275f2da&ip=&output=json";
var yqlRequestUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%20%22";
yqlRequestUrl += encodeURIComponent(apiRequestUrl);
yqlRequestUrl += "%22&format=json&callback=?";
$.getJSON(yqlRequestUrl,
function(jsonData) {
alert(jsonData.query.results.json.Ip);
});
Finally, this article can come handy: http://www.wait-till-i.com/2010/01/10/loading-external-content-with-ajax-using-jquery-and-yql/

Time out Ajax requests with jquery?

I think that you can set like on post and get methods in jquery timeouts but I am wondering does jquery have a global timeone like it has with ajax start and stop.
Like I would like to set it that if say a post or get or some sort of ajax request is running and it runs more then X amount of seconds. That a popup or something in that nature comes up saying that the "server is slow and the request has timed out" and kills that request.
Then the user can either try again or do something else.
Does jquery have something like this?
Thanks
The jQuery.ajax function is what you want. It gives you access to a pretty large set of options for making AJAX calls.
Specifically, you're going to want to make a call similar to
$.ajax({'complete': callbackFunction, 'url': 'foo/bar/', 'timeout': 5000, 'error': errorCallback});
The two options you're interested in are timeout and error. The entire documentation for the function is here. It's a bit more work than using the more standard get/post functions, but much more flexible.
The error function is very similar to the standard callback you use with any jQuery AJAX request. While the callback is called if the request succeeds, the error function is called when it fails (such as 404 errors, or when the timeout is hit). You'd use the error function to display your message to the user that their request has timed out. Full documentation on the function's arguments (which practically speaking, you probably won't need to use) is available on the $.ajax doc page (linked earlier).
Alternatively, you can set the timout globally on every AJAX call by using the jQuery.ajaxSetup function. Its arguments are exactly the same as the jQuery.ajax function, so you'd do something like this:
$.ajaxSetup({'timeout': 5000, 'error': errorCallback});
The upside is that you can continue using jQuery.get/jQuery.post, but the downside is that you have to do extra work to make AJAX calls without a timeout.
Yep, jQuery has a 'timeout' property (in milliseconds) you send the $.ajax() event:
http://www.bennadel.com/blog/1500-Catching-Timeout-Errors-With-jQuery-Powered-AJAX.htm
$.ajax(
{
method: "get",
url: "yourpage.php",
dataType: "json",
timeout: (3 * 1000), // 3 seconds
success: function(){
//success code here
},
error: function( request, strError ){
//error code here
}
}
);

Categories