Search code examples
javascriptajaxprototypejs

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}
});

Solution

  • 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.