Implementing an ajax call in clojurescript

Marc picture Marc · Dec 18, 2011 · Viewed 9.1k times · Source

I'm new to clojurescript and would like to do a deeper dive by implementing a previously written application purely in clojurescript, but am at a loss with respect to to implement an ajax call. Can anyone point me to an example online or provide me with a code snippet or two?

Answer

Marc picture Marc · Dec 20, 2011

January 22, 2016 update

Although it still works, the original answer is from a time when there was a general lack of ClojureScript solutions with more than 1 contributor. Rather than leveraging XhrIo directly, definitely consider using a well-maintained, feature-rich solution that wrappers it instead like cljs-ajax, as suggested by Mikhail D below!


Okay, So given that Clojurescript leverages Google's Closure JavaScript library, a quick search of the Closure Documentation yielded xhrIo as the proper method for generating AJAX calls:

Example using Closure's Asynchronous XMLHttpRequests with XhrIo

goog.net.XhrIo.send(url, opt_callback, opt_method, opt_content,
     opt_headers, opt_timeoutInterval)

A quick review of the Clojurescript source revealed the following function:

From src/cljs/clojure/browser/net.cljs in clojure / clojurescript

(defn xhr-connection
  "Returns an XhrIo connection"
  []
  (goog.net.XhrIo.))

So something along the lines of this should have the intended results:

(def xhr xhr-connection)

(defn myCallback [replyValue] 
  ... Do Something with replyValue
  ... for example: (someJsonFunc (.getResponseJson (.target replyValue))))

(defn ajax-json [url]
   (.send xhr url myCallback))

For JSONP, you can do something similar using the goog.net.Jsonp. See the link for details:

JSONP Closure API

Hope someone finds this helpful!