jQuery: a peculiarity of AJAX URLs

I was developing a simple AJAX search engine with jQuery but things didn't work in the sense that for each query I got more results than I did expect. Most of you know that the $.ajax() object has a member called data, which is basically a property that stores all the data passed along with an AJAX request. In my code, the data property had this form:

$.ajax({
  type: 'GET',
  url: 'http://app.com/search.php',
  data: '?query=' + query.toLowerCase() + '&search-options=' + searchOption,
  success: function(html) {
    // do something
  }
});

Do you see the point? The trailing question mark (?) prepended to the data string makes all the search query invalid or, more precisely, makes the query return a mismatched set of search results. If you remove the question mark, everything works just fine. So the point is: never prepend invalid tokens to the data string, because jQuery doesn't need them. On the contrary, you might actually get unexpected results if you do so.

Leave a Reply

Note: Only a member of this blog may post a comment.