Skip to content
Tomek Gryszkiewicz edited this page Mar 25, 2017 · 1 revision

AJAX

Question

I have the basics of drab down, however what is not documented is posting ajax, [...] currently I am posting ajax with a room name, and getting the id returned then placing into a local array, grabbing that array then using the ids to pull another query and update the view with the returned formatted room data, theres gotta be an easier way.

        var element = $('#elem');
        $.ajax({
            type: "POST",
            url: '/fetchroom',
            data: {
                roomname:$element.text().trim()
            },
            beforeSend: function(xhr) {
                xhr.setRequestHeader("X-CSRF-Token", CSRF_TOKEN);
            },
            success: function (data) {
                rooms.push(data.id)
            }
        });

Answer

AJAX is not documented because Drab does not use it at all. The idea is to get rid of all the client-side code, and write it at the server-side. So in your case, you can replace your ajax with such Drab Event Handler:

def fetchroom(socket, _sender) do
  roomname = socket |> select(:text, from: #elem”) |> String.trim
  id = get_room_id(roomname)
  # and post it back to the browser
  socket |> execjs(rooms.push(‘#{id});)
end

Also, if you really need to have your JS code, you can launch Drab Handler manually, using Drab.run_handler() method. See https://hexdocs.pm/drab/Drab.Core.html#module-running-elixir-code-from-the-browser

Clone this wiki locally