unlikenesses's avatar

Best practice for AJAX filters

I have a MySQL table, whose rows I display in a simple HTML grid. Let's say one field in this table is client. Above that I have a select tag, populated with these clients, and I have some jQuery that detects when the user selects something from this select element. The desired behaviour is to only show rows from my table whose client field matches the selected client.

I can think of 3 ways to do this, but I'm not sure which is the best. I'm not asking for code here, more which of these on principle you would go for (or any others):

  1. Give every row in the HTML table an ID based on its client, & upon select change, hide the rows which are not the selected client.

  2. On select change, use AJAX to post the selected client ID to a controller which returns the necessary HTML, and re-fill the table with $('.tableName').html(newData)

  3. On select change, use window.location.href (or similar) to redirect to a page with the client id in the query string.

(1) seems unsatisfactory because if I introduce pagination it will break. (2) seems unsatisfactory because it means building up a huge string of HTML, which is messy. (3) seems unsatisfactory because it involves creating a new route, and showing the client id in the query string, which seems untidy to me.

Any thoughts on this most appreciated!

0 likes
5 replies
martinbean's avatar

@unlikenesses The best approach would be to have an endpoint that returns the data as a JSON blob to keep responses as small as possible. You would then render this JSON blob using client-side templating in something like Mustache.

Thijmen's avatar

I'd go for 2. You don't need to use $('.table').html(newData). In your $.GET in jQuery you can iterate through the response and add them to the table.

unlikenesses's avatar

Thanks @martinbean and @Thijmen - sounds like you both think (2) with JSON is the way to go (unless I've misunderstood @martinbean's response).

Re. templating, I currently use Blade, is there some way to populate an HTML table from JSON in Blade without passing messy strings of HTML via jQuery?

XXX's avatar

@unlikenesses If you want to use Blade for this you can use that in your endpoint template and get the HTML of the endpoint page and replace that in your original place.

It's quick and dirty but it works.

1 like

Please or to participate in this conversation.