jxxcarlson

jxxcarlson

Inconsistent API requests

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

Marked As Solved

OvermindDL1

OvermindDL1

I’m seeing that too, but that is the forward for Absinthe.Plug.GraphiQL, which is the introspection helper path, but I’m not seeing a forward for forward "/graphql", Absinthe.Plug, schema: NoteApi.Schema, which is the actual path that you are having graphql communicate over?

Also Liked

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.

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

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.

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
shijith.k
I am trying to start a new phoenix project with elixir 1.9, but mix phx.new does not work. It says that ** (Mix) The task "phx.new" could...
New

Other popular topics Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement