How to reduce Wait time (TTFB) for MVC application - ajax

I have a html page with 7 divs, I am loading each div using ajax calls in order to load these cards parallelly. When I check from controller side, each div StoredProcedure is taking just 100-200 mSec, where as rendering each div is taking close to 2sec. When I check from Chrome Development tools, each request is taking so much of Waiting time (TTFB) and it looks to be each div is loading synchronously even though I am using the below code:
$.when($.ajax({
url: div1Url,
success: function (data) {
$("#div1").html(data);
}
}),
$.ajax({
url: div2Url,
success: function (data) {
$("#div2").html(data);
}
})
//Like this I am loading all divs...
).then(function () {
console.log('loaded');
});
<div id="div1"> Div1</div>
<div id="div2"> Div2</div>
<div id="div3"> Div3</div>
<div id="div4"> Div4</div>
<div id="div5"> Div5</div>
<div id="div6"> Div6</div>
<div id="div7"> Div7</div>
Please find the below my HTML rendered page and the timeline for the each component. Can someone suggest me how to reduce this waiting time to achieve performance.
PS: I have implemented gzip, Dynamic compression, Expires Headers, etc., and my site Grade is "A" when I tested with YSlow tool

Even if you are sending the AJAX requests concurrently, the ASP.NET MVC processes them as a queue, if you are using session data.
Try adding [SessionState(SessionStateBehavior.Disabled)] attribute to your controller.
Refer here: ASP.NET MVC 5 concurrent requests are queued even with disabled Session

They are so many reason for why an Ajax request can be slow.
I will try to put you on the right track.
First, you should specify that your request is of GET type, GET request are much faster !
You should also specify the type of data you are trying to recive, this will improve the speed.
Finely, you should call your function on complete and not on success
Given the three previous points :
$.ajax({
url : div2Url,
type : 'GET',
dataType : 'html',
success : function(code_html, statut){
},
error : function(resultat, statut, erreur){
},
complete : function(resultat, statut){
//Here you can treat your data
}
})
Also consider doing all you Ajax call for the same page in only one request. Gathering every data you need for you page in only one request will improve greatly your server performance. Then in page you can split your result for every div.
If this do not speed up your request, here are other points to consider :
Is it really your ajax request that is slow
or the request in server side ? (For example, request to database)
What type of data are you trying to receive ? Is it HTML ? Is it XML ? JSON ? (In most case, try to send the less data you can, for example if you have HTML to send, try to put the HTML on the page where you want to display the information and send only the data to be displayed)
Check the moment when you trigger the Ajax call. Maybe your doing the request at a bad moment.

Related

dynamicly fill table using zpt and ajax as update

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.
You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Send form to server in jquery

I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})

How do I send arbitrary JSON to node.js without a page reload?

My ultimate goal is to send an arbitrary JSON to node.js when a button is clicked. I currently only know how to send input from a form. Here's some code I put together to send form information:
function postForm() {
$('form').submit(function(e) {
e.preventDefault(); // no page reload
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data) { console.log('Code for handling response here.') },
'json'
);
});
}
Where the HTML looks like:
<form action='/send' method='post'>
<input name= "foo" type="radio" value=1>
<input type="submit" value="Submit">
</form>
And the relevant express/node.js code looks like:
app.post('/send', function(request, response) {
fs.appendFile('test.txt', JSON.stringify(request.body) + '\n', function(e) {
if(e) throw e;
console.log(request.body);
});
});
However, I don't know how to adapt this example to use data that is not from form input. To give context, I'm building a web-based user study, and I want to send various information collected about the user to node.js. I've tried variants of what was working for the form submission, but none of my attempts have been successful. My impression was that I could just swap out $(this).serialize() to any other data that the client can access, but I couldn't get this line of thought to work. I also tried altering some of the many .ajax() examples, but those always redirected the page which is undesirable, since my study will lose user-state information if the page refreshes.
I've done decent amount of client and server side programming, but I have next to no knowledge about how ajax works, which is proving rather problematic for solving this! And also rather silly since, often times, that's what glues the two together :)
Since you're using jQuery, sending data is simple – call $.post(url, data) from the button's click handler:
$('#somebutton').click(function() {
var data = { key: 'value', ... };
$.post('/send', data, function(res) {
// success callback
});
});
The browser will POST to url with a URL-encoded serialization of the data argument.
POST /send HTTP/1.1
Content-Type: application/x-www-form-urlencoded
...
key=value&...
Which Express' bodyParser will have no trouble with. Alternatively, you can tell jQuery to send a JSON serialization of data:
$.post('/send', data, function(res) {}, 'json');
In your case, it really doesn't matter how jQuery transmits the data (URL encoded or JSON), since bodyParser automatically deserializes both formats.

How do I render a view after POSTing data via AJAX?

I've built an app that works, and uses forms to submit data. Once submitted, the view then redirects back to display the change. Cool. Django 101. Now, instead of using forms, I'm using Ajax to submit the data via a POST call. This successfully saves the data to the database.
Now, the difficult (or maybe not, just hard to find) part is whether or not it's possible to tell Django to add the new item that has been submitted (via Ajax) to the current page, without a page refresh. At the moment, my app saves the data, and the item shows up on the page after a refresh, but this obviously isn't the required result.
If possible, I'd like to use exactly the same view and templates I'm using at the moment - essentially I'd like to know if there's a way to replace a normal HTTP request (which causes page refresh) with an Ajax call, and get the same result (using jQuery). I've hacked away at this for most of today, so any help would be appreciated, before I pull all of my hair out.
I had a very similar issue and this is how I got it working...
in views.py
from django.utils import simplejson
...
ctx = {some data to be returned to the page}
if ajax == True:
return HttpResponse(simplejson.dumps(ctx), mimetype='json')
then in the javascript
jQuery.ajax({
target: '#id_to_be_updated',
type: "POST",
url: "/",
dataType: 'json',
contentType: "text/javascript; charset=\"utf-8\"",
data: {
'foo':foo,
'bar':bar,
},
success: function(data){
$("#id_to_be_updated").append(data.foo);
}
});
Here's how I did it:
The page that has the form includes the form like so
contact.html
{% include "contact_form.html" %}
This way it's reusable.
Next I setup my view code (this view code assumes the contact form needs to be save to the db, hence the CreateView):
class ContactView(CreateView):
http_method_names = ['post']
template_name = "contact_form.html"
form_class = ContactForm
success_url = "contact_form_succes.html"
There are a few things to note here,
This view only accepts pots methods, because the form will be received through the contact.html page. For this view I've setup another template which is what we included in contact.html, the bare form.
contact_form.html
<form method="POST" action="/contact">{% crsf_token %}
{{ form.as_p }}
</form>
Now add the javascript to the contact.html page:
$("body").on("submit", 'form', function(event) {
event.preventDefault();
$("#contact").load($(this).attr("action"),
$(this).serializeArray(),
function(responseText, responseStatus) {
// response callback
});
});
This POSTS the form to the ContactView and replaces whatever is in between #contact, which is our form. You could not use jquery's .load function to achieve some what more fancy replacement of the html.
This code is based on an existing working project, but slightly modified to make explaining what happens easier.

Post or Get, which is more appropriate to call a simple asp page via jQuery Ajax

I have a html page that I need to call another asp page to get the date/hour via an ajax call. Which method would be better or best, Post or Get?
Since I am only retrieving a few bits of data and not sending any data to the page info is one method better or proper than the other?
This is the simple ASP page.
<%#LANGUAGE="VBSCRIPT"%>
<% Option Explicit %>
<%=Weekday(Date)%>
<%=Hour(Now)%>
And this is the Ajax call to the asp page above.
jQuery.ajax({
url: '/v/timecheck.asp',
type: 'GET',
cache: false,
success: function(data){
// do something with the data
},
error: function() {
//do something on error
return false;
}
})
The reason I have to make the Ajax call to this ASP page is I cannot query the server direct from this page.
My rule of thumb when deciding either one is:
The interaction involve database, POST
The interaction involve sensitive information, POST
Requesting simple data, GET
Sending user input, POST
Sending/requesting large data, POST
Clean URL, POST
As you can see, most cases involve POST for many reason. Such as in your case, you could use GET or POST. Either way, jQuery make calling both function easy.
A simpler $.POST
$.post("/v/timecheck.asp", function (data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
or simpler $.GET
$.get("/v/timecheck.asp", function(data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
I would use POST, I think there is a secirity reason in ASP.NET to use POST, but not sure if this relates to IIS (and possibly ASP)
The W3C have a paper with guidelines on when to use GET or POST at: http://www.w3.org/2001/tag/doc/whenToUseGet-20040321#checklist
Using a GET request allows the result to be cached by the browser whereas a POST request won't be cached and the page will be re-retrieved every time.
In your code example you are not changing any data as a result of the request and are only providing the day and hour, so using a GET and setting the cache HTTP headers to 1 hour would give you the best performance and reduce load on your server.

Resources