How to optimize multiple $.ajax({...}) function loading in Asp.net? - c#

I calling multiple function on page load in my asp.net web application.
All function run on page ready method
see the below code
$(document).ready(function(){
func1();
func2();
func3();
//.... so on.
});
function func1()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetText",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
function func2()
{
$.ajax({
type: "POST",
url: "Contents.asmx/GetTitles",
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
/some code
}
});
}
.... like wise others
For backend I using SQL server-05.
When page is loading It getting more time to load,
above functions takes 30+ seconds to load.
How to optimze function calling?..

You could aggregate all the queries into a new web method which will perform all the SQL queries at once. Then send a single AJAX request to this new method. And as far as your SQL server is concerned you could also send multiple SQL queries into a single round-trip. Try optimizing the SQL queries as much as possible. Also you could cache the results of some expensive queries.

As long as /some code is not too much there is not really much you can do. These ajax calls area light-weight. Your problem is probably in the backend, where you send your requests to.
To debug/profile your problem, first check your ajax requests. Check them in a web-tool like Firebug and see that your request is expected. There you can also check which of your requests takes how long.
As you now see your bottleneck (e.g. requesting Contents.asmx/GetTitles is what takes so long), check your server that provides that page. As you did not provide code of that one, we can not help you there. But that’s where you have to look for next.

Related

Consume ASP .Net WebService using HTML AJAX

I am trying to call a simple hellowworld function of ASP .NET WebService using JQuery AJAX call written in separate HTML file i.e. Not aspx file in ASP .NET.
Here is code of my AJAX call which works fine in aspx based web client.
$.ajax({
type: "POST",
url: "/Test1/RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#output").text(msg.d);
},
error: function (e) {
$("#output").html("WebSerivce error " + e.responseText);
}
});
I want to call same webservice and same method using .html file but it is returning error. I tried giving server address i.e. localhost but still no response.

jquery "async = true" call to .net web service not working asynchronously

I have a .NET webservice which I need to hit asynchronously from the jQuery and update the grid based on the result got from service. My problem here is that, the service hit is async only for the first time and the subsequent requests are sync (even after specifying async=true in the ajax call) as shown below
jQuery.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
var result = msg.d;
return callback(result);
},
error: $.callDotNetSM.onError
});
My .NET service method is something like below.
[WebMethod(EnableSession = true)]
public static string GetData()
{
}
So, please help me in calling the service asynchronously all the times. Any help is highly appreciated.
The page your WebMethod is being called on needs to have the following in the Page Directive:
<%# Page Async="true" EnableSessionState="False" %>
The reason for this is that ASP.NET locks the Session every time it is accessed so that it cannot run asynchronously.
Even if you do not use the Session in your WebMethod the page still thinks it uses it by default unless you tell it otherwise.
Edit:
Your problem could also be that you have EnableSession="true". You may just need to set it to false.

AJAX call in jQuery form submit function

I'm using ASP.NET MVC. So I have a form on my page:
<form id="MyForm" name="MyForm" method="post" action="http://www.mysite.com">
<input id="hdnType" name="hdnType" type="hidden" />
</form>
I'm using the jQuery submit action to do some validation before the form is posted. I also need to make an AJAX call to set "hdnType" based on other values from several dropdowns that I didn't include in this example:
$('#MyForm').submit(function()
{
if (!ValidForm())
return false;
$.ajax({
type: "POST",
url: '/Home/GetType',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
$('#hdnType').val(response);
}
});
return true;
}
Everything in the submit() function is supposed to run before the form posts. This was working correctly before I added that AJAX call, but now when the code reaches my AJAX call, the form posts before I can set "hdnType".
Is there a way around this?
The ajax call has a parameter async. By default it is true. This causes execution to not be held and the function to complete. Try changing it to
$.ajax({
async:false,
type: "POST",
url: '/Home/GetType',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
$('#hdnType').val(response);
}
});
This may be a poor practice as it will freeze the browser until it is done. Consider using an asyc call back function as Dave suggests
The success function is called asynchronously, after the ajax call gets a response. If you want to set hdnType before the form is posted you'd have to move that call outside the $.ajax call. It looks like you need to get the result for hdnType from your POST action first, in a separate function, then call submit on the form.

Can I validate an entity before saving the changes?

I have a very simple WCF Data Services application and I am doing some basic CRUD operations. I have a ChangeInterceptor on the entity set that is changing, but the object in the ChangeInterceptor is the current state in the database, not what is sent in the HTTP PUT. Is there a way to validate the properties of the object before saving it?
Here is my ChangeInterceptor:
[ChangeInterceptor("People")]
public void OnChangePerson(Person personChanging, UpdateOperations updateOperations) {
switch (updateOperations) {
case UpdateOperations.Change:
// personChanging is the database version here, not the changed version.
break;
default:
break;
}
}
Here is my client-side code (jQuery):
var data = {
FirstName: "NewFN",
LastName: "NewLN"
};
$.ajax({
type: "PUT",
url: serviceUrl + "/People(" + personID + ")",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert("Success!");
},
error: function (error) {
alert("An error occured");
}
});
Here is the JSON being sent to the server:
Here is the ChangeInterceptor when the message is received:
I have uploaded the code for this project here: http://andyjmay.com/test/2921612/ODataTest.zip
I downloaded your sample , reproed your issue and was able to see the latest updated value using this work-around for now.
While I investigate this internally,Can you change your code to use a Merge verb instead of a PUT ?
With this change, you should now be able to see the latest entity values being passed in to the ChangeInterceptors when you update the values via the jQuery client.
$.ajax({
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("X-Http-Method", "MERGE");
},
type: "POST",
url: serviceUrl + "/People(" + personID + ")",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
GetAllPeople();
},
error: function (error) {
alert(error);
}
});
WCF got some nice extension you can write like MessageInspector and ParameterInspector.
I'm sure one of them can help you validate stuff before the server even starts to work with tthe request.
If the service is EF based and the request is PUT, then the old value will be provided (this has to do with the way the EF provider is implemented and might be a bug, we will look into that some more). You can workaround this by sending a MERGE request instead. I verified, that in that case it works as expected (you get the new values). MERGE has a little different semantics, but it might work for you. PUT overwrites the entity, so if you didn't send a value for a given property it will be reset to its default value. MERGE only modifies the existing entity with the values from the payload, so if some property is not in the payload its value will be left untouched.
Hmm... you say personChanging is the database version, it should definitely be the updated version.
My tests (and people on the product team) tell me it should be the version that came over the wire. Could something else be going wrong?
For example could your property be Firstname instead of FirstName?

jQuery Postback with Webforms

We're redevloping a major section of our website and rather than use a 90k AJAX file I'd rather use a 19K jquery script.
I've seen the following articles;
Using jQuery for AJAX with ASP.NET
Webforms
jQuery autocomplete in ASP.NET webforms?
Autocomplete with ASP.Net MVC and
JQuery
The thing I don't get is how to do a postback to a specific method in either the code behind or another class.
I know in ASP.NET-MVC I can post back to a controller / action. How do I call a particular method in WebForms?
Something along the lines of; $.post("class and action", ( param:value}......
Any thoughts, code etc???
It is very easy to call specific methods in code-behind. Here is nice article with all the details by Dave.
Simply declare a method like this:
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
This is all you need in jQuery:
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg, status, xhr) {
// Do something interesting here.
}
});
Caveats:
WebMethod must be on a static method
Must stringify posted data if sending anything (i.e. JSON.stringify(yourDataObject)), will be deserialized according to method parameters
msg is the response, the return result from your method is in the property msg.d

Categories