Post or Get, which is more appropriate to call a simple asp page via jQuery Ajax - 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.

Related

Do I sent two requests to the ActionResult?

I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post

How to reduce Wait time (TTFB) for MVC application

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.

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

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.

Disable AJAX Caching

I am in a bit of a pickle right now. I am building a web page that will get data from a CGI backend. I have no control over the CGI backend, nor the server (so no mod_headers or mod_expires). Also, because of the parameters to the script, I cannot append a unique value (like '&089u0af0d98) to each request. The requests are AJAX using the XmlHttpRequest object. I have tried to set the 'If-Modified-Since' and 'Cache-Control' request headers unsuccessfully. Does anybody have any other ideas for how I can prevent the AJAX response from being cached by the browser?
You can send random parameters using POST, while sending the important vars using GET if you need to.
If you have problems with IE, I know that sending something with POST makes it to stop caching server responses
I use this javascript function ( which in turn uses jquery.ajax function )
the cache: false would do the trick.
This works perfectly for me , may be you can give it a try
function ajax_call(urlString)
{
ret_val="";
$.ajax
(
{
type: "GET",
url: urlString,
async:false,
cache:false,
dataType: 'html',
success: function(msg)
{
ret_val=msg;
},
error:function (xhr, textStatus, thrownError)
{
ret_val=xhr.readyState;
alert("status=" +xhr.status);
}
}
);
return ret_val;
}
I used $.ajaxSetup({ cache: false }); somewhere in my base html-page (default.aspx) in a non-frequent web-system and it worked fine. No pain-in-the-neck caching problems anymore.
I ran into this today, and found that if you want to keep to using get, you can add a hidden form element to the page and have JS set it's value to the current timestamp before submitting the query to ajax.
I add a form element something like this:
<input type="hidden" name="ie_sucks" id="ie_sucks", value="1" />
Then, in the function to submit the form via AJAX I set this hidden input to the current timestamp with something like this:
$('#ie_sucks').val(new Date().getTime());
The above code uses JQuery, so in pure JS it would be something like:
document.getElementById('ie_sucks').value = new Date().getTime();
This is not a pretty solution, but it does work.
I know jQuery's .ajax() call has a parameter called 'cache' which, if set to false, will force requested pages not to be cached by the browser. It's probably worth checking the jQuery source to see how they do it.
(I'm checking it now and will update if I find anything, but posting this answer early in case you or anybody else has better luck finding it.)

Resources