Thomas Skardal

Hello, computer.

Making ajax requests from ClojureScript

January 21, 2015

Recently I’ve played around with ClojureScript and my current idea is to create a multiplayer browser based snake game. I’m not sure if I’ll ever finish this project, but hey, at least I can blog about stuff I learn while doing it. I’ve put the source code on github so feel free to check it out.

Game communication will happen over websockets, but I’ll leave that alone for a while. The first thing I want to bring up is making simple ajax requests from the client. You could of course use JavaScript interop and jQuery or even XMLHttpRequest directly, but luckily, there are ClojureScript libraries.

I’ve used cljs-ajax. This library let you write code like this:

(GET "/something")
(POST "/something"
      {:params {:title "Hello, world!"
                :content "Important message"}})

This library support several formats such as json and edn (Extensible Data Notation). I wanted to use edn. To do that I had to ensure that the server could handle this. That was pretty straight forward and as the documentation suggesed, I’ve been using ring-middleware-format to wrap my ring/compojure handler.

In addition the requests need to be configured to use the correct format for both the request and the response: Note the response-format for the GET request!

(GET "/games" {:handler update-game-list :response-format :edn})

;; storing
(POST "/games"
        {:params {:game-name name
                  :created-by "Bob"}
         :format :edn}))

…and for the sake of completeness; here’s the compojure route definition to handle this

;; ...
(GET "/games" [] (active-games))
(POST "/games" {{name :game-name} :body-params} (create-gamename))

And that’s about it! The essence of this post can be seen in this commit. Here I’ve made it possible to create new games by providing a name and posting it to /games.