Search code examples
haskellyesodhaskell-warp

Using AJAX with the warp HTTP server


I'm having a bit of trouble trying to understand how WARP could potentially interact with the client-side. If I were to build my server-side via WARP, and had a Javascript client-side. Could I hypothetically use AJAX as the bridge between the client side and server-side?


Solution

  • Yes. AJAX doesn't need to know anything about your server to work. All it needs to do is request something at a url, and get a response.

    For example, suppose you are using jquery. Your Ajax request could look like:

    $.ajax({
      url: "/hello",
    }).done(function() { 
      $(this).addClass("done");
    });
    

    This is requesting something at url /hello. Then your Yesod app needs to serve something at /hello:

    mkYesod "yourapp" [parseRoutes|
    /hello HelloR GET
    |]
    
    getHomeR :: Handler RepHtml
    getHelloR = defaultLayout [whamlet|Hello!|]
    

    (I haven't used Yesod, so I can't claim that that code is accurate).

    Since WARP is a WAI handler, you can run any WAI application on it. Here's another example, this time using scotty:

    main = scotty 3000 $ do
      get "/hello" $ html "Hello!"