jxxcarlson

jxxcarlson

Hello! I have been using AJAX in the front end of my phoenix app to give flickerless updates when text is edited and rendered (see AJAX code below). The fields of data in the Ajax code are available in the reply to Phoenix in params, e.g., params["title"].

I would like to use the api server more generally and have been testing it with Postman. I do this by creating a key-value pair for the headers section, e.g., key=‘data’ value = {“title”: “TEST”, content: 'YADA YADA", …}. The info in the api server reply is in conn.req_headers, which is a list of key-value pairs as listed further down.

I can handle either case, but would like to formulate my requests and replies in a uniform manner – What do you advise?

AJAX CODE

$.ajax({
        url: "/api/notes/" + note_id,
        type: "put",
        data: {
            title: title,
            username: username,
            user_id: user_id,
            token : token,
            content: content,
            tag_string: tag_string,
            identifier: identifier,
        },
        headers: {
            "X-CSRF-TOKEN": csrf
        },
        dataType: "json",
        success: function (data) {

          console.log("OKKKK!");
          console.log(data);
          document.getElementById("rendered_text3a").innerHTML = data.rendered_text;

          newTypeset();

        }
    });

API REPLY TO POSTMAN REQUEST

[{"cache-control", "no-cache"},
 {"postman-token", "cee52325-1811-43b0-bd9c-413068e6b9d6"}, {"user_id", "9"},
 {"data",
  "{\"username\":\"jxxcarlson\",\"content\":\"This *is* a test\",\"tag_string\":\"foo,bar\",\"title\":\"Magick\"}"},
 {"token",
  "\"eyYADA_YADA_YADA_pPcVyg\""},
 {"username", "jxxcarlson"}, {"content", "This *is* a test"},
 {"title", "Magick"}, {"id", "1114"},
 {"user-agent", "PostmanRuntime/3.0.11-hotfix.2"}, {"accept", "*/*"},
 {"host", "localhost:4001"}, {"accept-encoding", "gzip, deflate"},
 {"content-length", "0"}, {"connection", "keep-alive"}]

NOTE added I extract info from conn.req_headers using the code below. Surely there is a better way!

   {:ok, data} = Poison.Parser.parse conn2value(conn, "data")

    defp key2value(list, key) do
      pair =  Enum.filter(list, fn(pair) -> {k, v} = pair; k == key end)
      [{_,value}] = pair
      value
    end

    defp conn2value(conn, key) do
      key2value(conn.req_headers, key)
    end

Showing Posts 1 to 10

OvermindDL1

OvermindDL1

Well the Drab library for Elixir would let Elixir control the page for the same flickerless updates.

Absinthe for Elixir would let you use GraphQL instead of AJAX, which would be MUCH more uniform to use and faster to process as well.

Or for still doing it as you are I would transfer the data in a post body and read it back from the body, I’d not mess with headers.

But still, parsing json is still json, I’d go with GraphQL instead of json straight.

jxxcarlson

jxxcarlson OP

Thanks! I will start off by investigating GraphQL

OvermindDL1

OvermindDL1

A quick short, GraphQL is a json-like query language developed by facebook, you send the query to the server and the server fulfills it and send back json in the exact format the client wants it in based on the query.

Absinthe is a wonderous Elixir library that manages all the horror of it for you, fully typed and correct and handled and you just respond with the specific data that Absinthe asks you and it munges it in to how the client wants. :slight_smile:

jxxcarlson

jxxcarlson OP

re GraphQL – excellent! I hate my AJAX code. It is totally Rube Goldberg. I’ll check out Absinthe as well.

OvermindDL1

OvermindDL1

There is even an absinthe over phoenix sockets library out around somewhere too for even faster speed. There are a ton of javascript libraries to work with GraphQL too that make it almost stupid-simple to use. The Apollo front-end framework is practically built for GraphQL too (and there is a phoenix websocket thing for it as well).

jxxcarlson

jxxcarlson OP

Stupid simple is what I need:-)

I’ll take a look at these others as well – I haven’t used sockets yet, but speed is important in this instance – real time editing / rendering of math/science text.

jxxcarlson

jxxcarlson OP

I’ve run into some trouble getting absinthe to work on my app. The error message in the logs is

[debug] ** (Phoenix.Router.NoRouteError) no route found for POST /graphql (LookupPhoenix.Router)
    (lookup_phoenix) web/router.ex:1: LookupPhoenix.Router.match_route/4
    (lookup_phoenix) web/router.ex:1: LookupPhoenix.Router.do_call/2
    (lookup_phoenix) lib/lookup_phoenix/endpoint.ex:1: LookupPhoenix.Endpoint.phoenix_pipeline/1
    (lookup_phoenix) lib/plug/debugger.ex:123: LookupPhoenix.Endpoint."call (overridable 3)"/2
    (lookup_phoenix) lib/lookup_phoenix/endpoint.ex:1: LookupPhoenix.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) /Users/carlson/dev/elixir/ns_umbrella/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

The request in graphiQL is POST http://localhost:4001/graphql and the error message there is

SyntaxError: Unexpected token < in JSON at position 0

In web/router.ex I have the code

  forward "/graphiql", Absinthe.Plug.GraphiQL,
      schema: NoteApi.Schema

and in phoenix.router.ex I have added the code

  defmodule NoteApi.Router do
      use NoteApi.Web, :router
      # ...
      forward "/graphql", Absinthe.Plug,
        schema: NoteApi.Schema
      # ...
    end

What would you suggest?

OvermindDL1

OvermindDL1

Do you have this on github somewhere? The reason is that no route found for POST /graphql really implies that your forward "/graphql", Absinthe.Plug.... line is not in your main router (this is not an absinthe issue, purely routing setup, normal Phoenix stuff).

jxxcarlson

jxxcarlson OP

Let me fiddle with it a bit – if I fail, I will push my graphQL branch to GitHub

jxxcarlson

jxxcarlson OP

Well, my experiment didn’t work – here is the github link:

https://github.com/jxxcarlson/ns_umbrella

The code is in the graphQL branch — look in apps/lookupPhoenix

the forward code is at

https://github.com/jxxcarlson/ns_umbrella/blob/graphQL/apps/lookup_phoenix/web/router.ex#L30

Thanks!

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews