$.ajaxPrefilter() Vs $.ajaxSetup() - jQuery Ajax - javascript

While learning through ajax in jQuery, I came across 2 terms, viz., $.ajaxPrefilter() and $.ajaxSetup(). All I can find out is that these make some changes in AJAX before loading or making call to $.ajax().
Can someone simplify and explain these terms in easiest form along with a slight comparison of the two?

$.ajaxSetup() - Set default values for future Ajax requests. You could, for example, set the ajax URL that you always want to use for every request here.
Example:
$.ajaxSetup({
// Always use this URL for every request
url: "http://example.com/ajax.php"
});
$.ajaxPrefilter() - Modify existing options before each request is sent. You could, for example, append a query string component to every ajax request that is sent out.
Example:
$.ajaxPrefilter( function(options) {
// Always add "?debug=1" to every URL
options.url += (options.url.indexOf("?") < 0 ? : "?" : "&") + "debug=1";
});

$.ajaxSetup simply takes an options object, and uses it as the defaults for future $.ajax() calls (and other calls that are shortcuts for this, like $.get). For instance,
$.ajaxSetup( { dataType: 'json' });
makes this the default dataType for future calls.
$.ajaxPrefilter lets you run a custom function before sending each AJAX request to the server. It can examine the options to that call, and then change them in any way that it wants. So it provides much more flexibility and control than $.ajaxSetup.

Related

JavaScript / Jquery call controller synchroneousely

I need to synchronously call a controller (url) in my Javascript. I could do this with an Ajax function like so:
$.ajax({
type: 'POST',
url: BASE + '/publication/storeWorldCat',
data: data,
success: success,
dataType: dataType,
async:false
});
I don't understand why I should use an Ajax function with a async:false parameter as Ajax is asynchronous by definition. $post() is asynchronous too.
Is there a better way?
Thanks for your help!
Looking at the documentation of jQuery.ajax (quoting) :
By default, all requests are sent
asynchronously (i.e. this is set to
true by default). If you need
synchronous requests, set this option
to false.
Granted, AJAX stands for Asynchronous Javascript and XML so any request sent in Javascript that is not sent asynchronously or does not use XML as the data format should technically not be called an AJAX request. With the popularity of JSON nowadays, it looks like the $.ajax function is REALLY badly named since it allows any data format.
But many other acronyms are chosen to be easy to pronounce at the cost of not being totally correct, and I think we can live with it. So to answer your questions:
Why has the jQuery team decided to name this function ajax? Because this acronym was already used by everyone, regardless of the data format used and the "synchronousness". Why is everyone using this acronym wrongly? Probably because it did not make sense to make a new acronym for each data format, each time with an optional 'A' for whether it is asynchronous.
Why [you] should use an Ajax function with a async:false parameter as Ajax is asynchronous by definition?
Well, you don't have to:
$.sendRequest = $.ajax
And now you can use a function with a better name in your code. You can even change the default behaviour:
$.sendRequest = function(options) {
if (typeof options.async === undefined) {
options.async = false;
}
$.ajax.apply($, arguments);
}

abort the right ajax

My question is probably nooby but I really cannot find an answer actually.
I want to use abort() method on a specific ajax. However i always use request=$.ajax...for all my requests and the request.abort() cancell ALL my ajax, intead of only the one i want.
Is there a way to point on the right one by naming it or something?
here is my code
request.abort();
request = $.ajax({
url: "getphp/gettooltip.php",
type: "GET",
data: {db : db, id : url.substring(url.lastIndexOf('=')+1)},
dataType: "JSON"
});
request.done(function(msg){
d3lttFillInTooltip(msg,db)
$('#d3ltttooltipdiv').css('visibility','visible');
});
I absolutely need to cancel the last call of this same ajax before running this one.
Any help would be welcome :)
You need to change your code so that you are not simply assigning request=$.ajax({...}); for every single call. You need some sort of list or mapping of requests. How you implement this depends on when you need to abort requests. For example, if you just wanted to have a stack of requests, so that you could easily abort the last request, you could do something like this:
var requests = [];
requests.push($.ajax({
// request 1
...
}));
requests.push($.ajax({
// request 2
...
}));
requests.push($.ajax({
// request 3
...
}));
requests.pop().abort(); //aborts request 3
// or...
requests.shift().abort(); //aborts request 1
If this doesn't help you, please provide more info on when you need to abort requests. Bottom line -- don't set request to every single ajax request you make if you want to be able to target specific requests.
Use a different variable for each jqXHR object.

Preferred method for waiting for AJAX in JavaScript

I find myself having to get around waiting for AJAX in jQuery often these days. Problem is, I have to do loops and crap to wait for them. What are some ways that I can wait for the AJAX event to finish before executing code (preferably without making extra functions)?
Generally, if there is a chance that a repeating AJAX request may not be finished before it is called again, I use a flag to prevent overlapping requests.
First, define the flag and set it initially as false. Whenever you are sending your AJAX request, check to see if this flag is false. If it is, then proceed with the request - not before setting the flag to true mind. Once the AJAX request has completed, set the flag back to false.
Using the above method, only one instance of the AJAX query will run at once. I'm sure jQuery must have a way of seeing if there is an AJAX request being processed already or not, but I'm a MooTools man.
What method are you using to make AJAX calls? If you use the built in $.ajax(), you can set the success property to a callback function which will be called once the AJAX request returns successfully. There is also the complete callback which will always be called whether it succeeds or fails.
From the jQuery API:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
There is also a complete option that you can use.
http://api.jquery.com/jQuery.ajax/

Difference between $("#id").load and $.ajax?

Does anyone know what is the difference between $("#id").load and $.ajax?
Let me clarify things for you a little bit :
$.ajax() is the basic and low-level ajax function jQuery provides which means you can do what ever you want to like you can work with XmlHttpRequest object. But once upon a time jQuery Developers thought that actually besides $.ajax(), they could provide more specific methods to developers so they wouldn't need to pass more parameters to make $.ajax() method work the way they want. For example they said instead of passing json as a parameter to $.ajax() to indicate return data type, they provided $.getJSON() so we would all know that the return type we expected was json, or instead of indicating send method as post or get, you could use $.post() or $.get() respectively.
So load() is the same thing, it can help you inject html data into your html. with load() method you know that an html portion is being expected.
Isn't that cool ?
I think I've been fallen in love.
For more information, you can visit jquery.com, they are even providing their new library and api tutorial page.
Edit :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
is the same as below :
$.post("some.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Now as you can see it is the simplified version of $.ajax(), to make post call, you need to pass some information of send method type which is post as shown at the first example but instead of doing this you can use $.post() because you know what you are doing is post so this version is more simplified and easy to work on.
But don't forget something. Except for load(), all other ajax methods return XHR (XmlHttpRequest instance) so you can treat them as if you were working with XmlHttpRequest, actually you are working with it tho :) and but load() returns jQuery which means :
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
in the example above, you can easly inject the return html into #objectID element. Isn't it cool ? If it wasn't returning jQuery, you should have been working with callback function where you probably get the result out of like data object and inject it manually into the html element you want. So it would be hassle but with $.load() method, it is really simplified in jQuery.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
You can even post parameters, so according to those parameters you can do some work at server-side and send html portion back to the client and your cute jQuery code takes it and inject it into #feeds html element in the example right above.
load() initiates an Ajax request to retrieve HTML that, when returned, is set to the given selector.
All the jQuery Ajax functions are simply wrappers for $.ajax() so:
$("#id").load(...);
is probably equivalent to:
$.ajax({
url: "...",
dataType: "html",
success: function(data) {
$("#id").html(data);
}
});
A more concise summary and the most important difference is that $.ajax allows you to set content-type and datatype.
These two are important for making JSON requests, or XML requests. ASP.NET is more fussy with a missing content-type field (atleast when you use [WebMethod]) and will simply return the HTML of the page instead of JSON.
$.load() is intended to simply return straight HTML. $.ajax also gives you
caching
error handling
filtering of data
password
plus others.
From the documentation ...
$(selector).load(..)
Load HTML from a remote file and inject it into the DOM.
$.ajax(...)
Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
load is specifically for fetching (via GET unless parameters are provided, then POST is used) an HTML page and directly inserting it into the selected nodes (those selected by the $(selector) portion of $(selector).load(...).
$.ajax(...) is a more general method that allows you to make GET and POST requests, and does nothing specific with the response.
I encourage you to read the documentation.
Here's the source code for the load function: http://github.com/jquery/jquery/blob/master/src/ajax.js#L15
As you can see, it's a $ajax with some options handling. In other words, a convenience method.
The above answer may not be valid anymore in light of the use of deferred and promise objects. I believe that with .ajax you can use .when but you cannot do so with .load. In short, I believe that .ajax is more powerful than .load. For example:
some_promise = $.ajax({....});
.when(some_promise).done(function(){.... });
You get more granular control over the html loading. There is also .fail and .always for failure and "no matter what" cases. You don't get this in load. Hope I am correct on this.

Is there a Request.IsMvcAjaxRequest() equivalent for jQuery?

I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.

Categories