I have this piece of code
function getMesssages(id,c) {
function waitForServerCall(id,c) {
$.get(href("~/polling/" + id), function (response) {
var r = c(response);
if (r) {
return false;
}
waitForServerCall(id);
});
}
waitForServerCall(id,c);
$.post(href("~/batch/export/?batches=3344&pollid=" + id), function (response) {
c(response);
cancelCall = true;
});
}
The $.get inside the waitForServerCall method only get execute when the $.post recive the server response. Why?
This is the ajaxSettings:
accepts: Object
async: true
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
contents: Object
converters: Object
flatOptions: Object
global: true
isLocal: false
jsonp: "callback"
jsonpCallback: ()
processData: true
responseFields: Object
type: "GET"
url: "http://localhost:59161/"
xhr: In()
__proto__: Object
Update.
What i am doing is long polling, the post request is a long running process so i need to know some events that the server will trigger, the waitForServerCall method notify the client about the events that occured. But since the $.get method execute once the $.post response is recive, the notification process don't work.
Update 1:
Im using .NET 4.0 and Jquery 1.9.1.
Yes, the $.get request gets execute first but not response is recive until the $.post get the response. Once the $.post get the response, $.get execute correctly. But I'm expecting the $.get to get the server response even if the $.post has not get any response yet.
So here is the answer of why.
All the credits goes to the author of this article:
http://josefottosson.se/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Related
I'm trying to perform AngularJS post request via $http. My code looks like this:
$http({
url: "cgi-bin/post_event.pl",
method: "POST",
data : jsonToSend,
headers : {
'Content-Type' : "application/json",
}
}).success(function(data, status, headers, config) {
if (status === 200) {
console.log(data);
} else {
console.log(data);
}
}).error(function(data, status, headers, config) {
console.log(data);
});
While looking via Firebug I see that this part of code gets executed, but none request is triggered towards server.
Only when I click it again, request hits server and success method is being called.
Anyone knows why's that? Or maybe I'm doing something wrong here...
This code with jQuery works fine:
$.ajax({
url: "cgi-bin/post_event.pl",
type: "POST",
contentType : "application/json",
data : JSON.stringify(jsonToSend),
success : function (data) {
console.log(data);
CurrentEvent.eventname = "";
CurrentEvent.starttime = "";
CurrentEvent.eventLocation.longitude = "";
CurrentEvent.eventLocation.latitude = "";
$window.location.href = "#/host/my_events";
},
error : function (data) {
// add error to $rootScope.errors
}
});
EDIT: Ah, sorry, I should be more detailed. This is called as callback after successful ajax request. Rest of the this code is just constructing jsonToSend.
So first time this part is being called I can see in firebug it constructs $http request but I can't see it triggered on server.
Next time I click on a button that does first time ajax request success method of this one is called (but id doesn't call it via callback from ajax, but it goes directly into success method)
I am working in ASP.Net MVC. I have following Javascript code in which i am calling a controller-method which returns a view. I want to send parameters to a controller method which re
function fun(p1,p2)
{
// code here to call controller method which returns view
}
public ActionResult ProblemDetails(p1,p2)
{
// here goes some code.
return View();
}
Please tell me the code which can be used to call controller and send parameters too.
Action Method
public ActionResult SendStream(string a, string b)
{
}
JQuery/JSON
Please note that Get Verb will not support complex Data parameters due to it's Query string length constraint. So use POST Verb instead of GET Verb while sending large data
$.ajax({
url: url,
data: JSON.stringify({ a: "a", b: "b" }), //Two String Parameters
type: 'GET', //For Submit, use POST
contentType: 'application/json, charset=utf-8',
dataType: 'json'
}).done(function (data) {
//Success Callback
}).fail(function (data) {
//Failed Callback
}).always(function(data) {
//Request completed Callback
});
Are you perhaps looking to return a Partial View? You can use jQuery ajax to post to a controller method that returns a Partial View (html). You can then render that HTML on the page.
http://mazharkaunain.blogspot.com/2011/04/aspnet-mvc-render-partial-view-using.html
jQuery.get is the shorthand way to achieve this.
function fun(p1,p2)
{
var url = '/controller/ProblemDetails?p1=' + p1 + '&p2=' + p2;
$.get(url, function (data) {
// data will be your response as html
});
}
I might also suggest to have the action return PartialView() instead of View() since you will not return the layout along with the response. It all depends on your intentions for the returned html.
There are several ways to do it.
For example Ajax:
Quick note first: Make sure that in your MVC routing configuration you have a route configured to reflect the following url below:
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2' //url to your action method
$.ajax({
url:url,
type:'post' or 'get', //(depending on how you're doing this. If post you can pass data internally instead of query string ),
dataType:'html', //(for example)
success:function(data){
//data here will contain your View info so you can append it do div for example. You can use JQuery .html() function for that
error: function (xhr) {
//catch error
}
}
})
}
Another way, in case if you want to load your View data to DIV is to use JQUery functions such as .load();
function fun(p1,p2)
{
var url = '/ControllerName/ProblemDetails?p1=p1&p2=p2';
$('#YourDivTagForExample').load(url);
}
$.ajax call can also be abbriviated to $.get, $.post or $.getJSON depending on what kind of a call you want to make to your action method. There is a lot more to it too.
Finally make sure to take a look at this answer. Your question was actually already answered in full:
Correct way to handle Ajax calls in ASP.Net MVC 3
Use JSONResult instead of ActionResult and Manipulate return data in javascript.
I have a generic-http-handler and I am calling it from jQuery.
My handler only insert values in database but does not return anything.
I am calling the handler as follow
function InsertAnswerLog(url) {
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: { 'Url': url, 'LogType': "logtype" },
success: function (data) {
},
error: function (Error) {
}
});
}
Everything is working fine for me.
But is it the best way to post the values to the server.
Or can I use it in a better way.
it seems the type of data you are sending is JSON encoded try serializing the data in this form before sending and then on the server side you should encode the data before sending it back.
serializing before sending to server
function InsertAnswerLog(url) {
var DatatoSend = { 'Url': url, 'LogType': "logtype" } ;
$.ajax({
type: "POST",
url: "../Services/Handler.ashx",
data: {Jsondata: JSON.stringify(DatatoSend)},
success: function (data) {
},
error: function (Error) {
}
});
}
now on the sever side scipt
// NB: i use PHP not asp.net but it think it should be something like
Json.decode(Jsondata);
// do what you want to do with the data
// to send response back to page
Json.encode(Resonponse);
// then you could in php echo or equivalent in asp send out the data
It is important that you decode the json data on the server-side script and when a response is to be sent it should be encoded back it JSON form for it to be understood as a returned json data.
I hope this helps.
I have an application where around 20 http generic handler are used for ajax call.
I have used IReadOnlySessionState for accessing the session in my handlers.Everything is working fine.
But when session expires my handler is returning some html as it redirects to default page and html of default page is sent back in the response.
To overcome this issue.
I have checked the session variable in the handler and if it is null the I have written
context.Response.Write("logout")
And I check in jQuery ajax weather it is logout or anything else.
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data) { checklogout(data); $("#loading").hide(); },
error: function () { $("#loading").hide(); },
async: false
});
If it is logout then I have used location to redirect to login page.
I am using form-authentication to authenticate user.
Is there any better approach for checking and redirecting to login page using jquery-ajax call.
You have your handlers in a directory that automatically control by the authentication of asp.net.
What I should do is to not let automatically control by the asp.net authentication by setup that on web.config so the call to the handler will done ether the user is logged in ether not, and inside the handlers I will check for that, if the user that call that handler have the session and the authentication.
Then in the case that the user did not have the authentication to read that handler I return a simple flag to my ajax call, then recognize and make redirect, eg as:
$.ajax({
url: "myhandler.ashx",
contentType: "application/json; charset=utf-8",
success: function (data)
{
if(data.redirectToLogin == true)
{
window.location = "/login.aspx"
}
else
{
// do the rest job
}
},
error: function ()
{
$("#loading").hide();
}
});
I'm using a web service with an ASP page. I'd like to keep most of what is going on here happening on the service, but I need to call one function from the codebehind. How do I do this and keep it asynch.?
How do you register a callback to codebehind that is called when the service call completes?
Thanks!!
EDIT:
EXTRA INFO: I call an asmx web service using $.ajax from the jQuery library. I'd like to avoid too many changes, but again my end result must be calling a function from the service and upon completion calling a codebehind function, all as asynchronous as possible.
$.ajax({
type: "POST",
url: "WebService.asmx/InsertClient",
contentType: "application/json; charset=utf-8",
data: insertdata,
dataType: "json",
success: function (msg) {
pkey = msg.d;
inserted();
return false;
},
error: function (msg) {
alert(msg.status + msg);
return false;
}
});
All of that happens correctly and everything works, but I'm just having trouble trying to work in an asynchronous call to codebehind - because I need to update a dropdown to refresh its datasource - as here I have just added a new entry.
If you are calling the webservice from JS, you can hookup a OnSuccess event in JS and then do a __doPostback to your page from Javascript.
example:
`function testCall() {
WebServiceProxy.GetDocuments(param01, this.onSucceed, this.onFailure);
}
function onSucceed (result) {
// if result is ok
__doPostback(clientID, params);
}
function onFailure (result) {
}`
In the asp Page/UserControl you need to implement IPostBackEventHandler. For example that way:
public void RaisePostBackEvent( string eventArgument )
{
switch( eventArgument )
{
case "CallComplete":
OnWebServiceCompleted( new WebServiceCompletedEventArgs( value1 ) );
break;
default:
break;
}
}