Best way to submit search criteria to the server with AJAX?
If you wrap your HTML in a <form>
tag, you can easily use the $.serializeArray()
function in jQuery.
http://api.jquery.com/serializeArray/
$.serializeArray()
creates a JavaScript object literal in the form of:
[ {name: a, value:1}, {name: b, value: 2}, ...]
This is done, I believe, because your form could have multiple fields with the same name. An associative array wouldn't support this.
I'd recommend that you send your data to your server in a JSON format (using serializeArray
or some other method) rather than a plain string. JSON is more standardized and can handle escaping characters. If you're using pipe-delimited strings, then you have to take into account when a user wants to submit a pipe (|
) to the server. Then you get into situations where you have crazy delimiters like ||**
between values. (I've seen this -- it's ugly!). Stick with JSON.
If you'd prefer a more querystring-like format (e.g. a=1&b=2&c=3) that you can include in your request body, you can use $.serialize()
.
Google uses querystrings, the equivalent of:
search?name=John&option=2&date=2010-10-10
This has a few advantages:
- searches can be bookmarked or emailed as links
- its appropriate that a search is a GET request rather than a POST, since it doesn't change the state on the server
- it gives you an easy "poor man's API" whereby a request to perform a particular search can be generated very simply
disadvantages:
- you have to URL-encode everything
- search strings get archived in logs, etc.
That said, if you're choosing between the options you gave, I would choose JSON: it's a bit longer, but I think it will save you a lot of headaches to have explicitly named parameters (rather than relying on location within a string).