james
james

Reputation: 4049

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

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.

Upvotes: 1

Views: 65

Answers (2)

Anthony L
Anthony L

Reputation: 2169

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

Upvotes: 0

Rodrigo Moya
Rodrigo Moya

Reputation: 31

Did you try to set the respond_to with .json?

format.json {render json: @result.to_json}

Upvotes: 1

Related Questions