Home Rails remote renders a page of json and the JS ajax handler doesn't catch
Reply: 2

Rails remote renders a page of json and the JS ajax handler doesn't catch

james
1#
james Published in 2018-02-14 00:11:14Z

I would like a form to post remotely, and then get some JSON back that my JS knows what to do with. Code:

<%= form_tag '/admin/order_lookup', remote: true, authenticity_token: true, id: "order-lookup-submit" do -%>
  <%= text_field_tag 'contact_string' %>
  <%= submit_tag 'Submit' %>
<% end -%>

$("#order-lookup-submit").on("ajax:success", function(e, data, status, xhr) { 
  alert("in success")
})

def order_lookup
  # some code
  render json: @result
end

When I do the POST, what happens is I correctly get the JSON, but in a page of just JSON (URL: http://localhost:3000/admin/order_lookup).

Obviously I don't want that, I want the ajax event handler to catch the JSON. What am I doing wrong?

I've tried

respond_to do |format|
  format.js {render json: @result}
end

in like every possible way, and I keep getting ActionController:UnknownFormat. Haven't successfully debugged that according to conventional logic either.

Anthony L
2#
Anthony L Reply to 2018-02-14 01:46:17Z

Try changing your form_tag to the following:

form_tag '/admin/order_lookup.json', remote: true, authenticity_token: true, id: "order-lookup-submit"

Notice the appended json on the location.

I've created a demo app to illustrate this working.

testing.js

$(document).ready(function(){
  $("#order-lookup-submit").on("ajax:success",function(event){
    alert("success");
  }).on("ajax:error",function(event,x,y){
    alert("error");
  });
});

order_lookup.html.haml

= form_tag '/admin/order_lookup.json', remote: true, authenticity_token: true, id: "order-lookup-submit" do 
  = hidden_field_tag "testing", "testing"
  = submit_tag "submit"

Controller

class TestingController < ApplicationController
   def order_lookup
     return render json: {hi: "hi"}
   end
end

Routes

Rails.application.routes.draw do
   root "testing#index"
   post "admin/order_lookup" => "testing#order_lookup"
end
Rodrigo Moya
3#
Rodrigo Moya Reply to 2018-02-14 01:10:08Z

Did you try to set the respond_to with .json?

format.json {render json: @result.to_json}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307439 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO