Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax GET requests: use parameters or put data in URL?

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}
});
like image 443
Diodeus - James MacFarlane Avatar asked Oct 20 '08 13:10

Diodeus - James MacFarlane


2 Answers

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.

like image 195
Evan DiBiase Avatar answered Sep 18 '22 00:09

Evan DiBiase


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()
}
like image 39
Mark Biek Avatar answered Sep 20 '22 00:09

Mark Biek