Pass JQuery variable to phoenix view parameter

I would like to pass a variable from jquery and use it with the phoenix path helpers to call an api endpoint which I am want to consume using jquery $.get functions. I can’t find any examples on how to pass that variable to Phoenix. Is this possible and if so, how can I go about it?

My sample code looks something like this:

function get_app_details(application_id){
         $.get("<%= api_app_view_path(@conn, :api_view, application_id) %>")
          .done(function( data ) {
              console.log( "Data Loaded: " + data );
          })
          .fail(function() {
              console.log( "error" );
          })
     }
1 Like

Gets turned into:

  $.get("/the/path")

Things in <% %> brackets are entirely gone at ‘compile’-time (technically replaced with some internal functionality). The javascript on the other hand gets run on the ‘client’, not the server. If you want a path you either need to encode a list of paths with an appropriate key, or do a lookup back to the server (websockets, REST, whatever) to do it.

In this case your jquery get call could just pass it as a query argument like:

$.get("<%= api_app_view_path(@conn, :api_view) %>", ""+application_id)

You’d have to make a route to handle that, or if it is a normal phoenix’ish resource then you could do:

$.get("<%= api_app_view_path(@conn, :api_view) %>/"+application_id)

And there are a dozen other ways too, depends on your use.

2 Likes