What's the advantage of passing data as parameters vs part of the URL in an Ajax GET request?
Using parameters:
var ajax = new Ajax.Request('server.php',{
parameters: 'store=11200&product=Meat',
onSuccess: function(myData){whatever}
});
Using URL:
var ajax = new Ajax.Request('server.php?store=11200&product=Meat',{
onSuccess: function(myData){whatever}
});
One advantage to using the parameters
argument is that you can pass it a Hash
-like object instead of as a string. (If you do this, though, make sure so set the method
parameter to "GET"
, as the default method for Prototype Ajax requests is POST; see the Prototype Introduction to Ajax for more details.)
Another advantage, which is more in-line with the example that you gave, is that you can separate the request URL from the options that are sent to it. This might be useful if, for example, you need to send a bunch of similar requests to several different URLs. (In that case, having a common parameters Hash
that you modify for each request might be more useful, than using a parameter string, as well.)
For more information, see the Prototype documentation of Ajax options.
One of my favorite uses of parameters is to pass in all fields of a form without explicitly listing them:
new Ajax.Request('/myurl.php', {
method: 'get',
parameters: $('myForm').serialize(),
onSuccess: successFunc(),
onFailure: failFunc()
}
To answer this, you should know the way the parameters work. HTTP basically (I know, there are more) has two methods to request data: GET and POST.
For GET, parameters are appended to the resource you request, like you did in your code above: /my/resource/name?para1=bla. Here, there is no difference if you append if directly to the resource name or use the parameters option. GET is normally used to request data (Its GET ;)
For POST, the parameters are written seperate from the resource in the HTTP body. For this, you must use the parameters option. POST is used to send (huge) data.
To specify which request method to use, use the method option.
Note: The GET resource has (depending from server to server) a hard limit on the length. So NEVER send much data using GET.
You can also use the format:
var ajax = new Ajax.Request('server.php',{
parameters: {
store: 11200,
product: "Meat"
}
onSuccess: function(myData){whatever}
});
On advantage of doing it this way is that you can change from a GET to a POST without changing the URL.
It doesn't really matter from a technical standpoint on this other than formatting and preference because get requests always have the data in the URL. The parameters are just a convenient way of building the GET request.