Reputation: 469
I have the following jQuery:
var request = $.get("getPerforceSuites");
request.success(function(result){
alert("res: " + result)
})
request.error(function(jqXHR, textStatus, errorThrown) {
alert ("err: " + errorThrown);
})
And the following entry in routes.rb:
get "getPerforceSuites", to: "perforce_sync#getPerforce"
and in my perforce_sync_controller.rb:
def getPerforce
# return getRemoteSuites
puts "++++++++++++++++++++++++++++++++++++++"
puts "Called getPerforce"
puts "++++++++++++++++++++++++++++++++++++++"
return "Hi!"
end
Initially this wasn't working - until I created an empty getPerforce.erb.html file in /views/perforce_sync... Now I can confidently say The getPerforce action is definitely being called, since the 3 "puts" lines appear in the rails server log. However, I had expected the "alert("res: " + result)" to show "Hi!"... But instead, I'm getting a whole heap of HTML, seemingly a document header (but from what file, I've no idea!):
res: <!DOCTYPE html>
<html>
<head>
<title>Test1</title>
<link data-turbolinks-track="true" href="/assets/application.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/authentication.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/bootstrap.css?body=1" media="all" rel="stylesheet" /> ***... SNIP ... ***
Can anyone explain what I'm getting wrong here? I'm kinda new to jQuery - but no amount of googling has resulted in my recognising the issue!
Thanks!
Upvotes: 1
Views: 60
Reputation: 76774
I would suggest the reason why the getPerforce.js.erb
is outputting an <html>
header is because the server is already outputting content with your puts
commands
HTML
Although the official terminology escapes me, you must remember Rails is a framework based on HTTP -- meaning any outputted has to be transmitted to the client
As such, if you're outputting text, it's got to be rendered, which I would guess is done with the Rails HTML rendering engine
Controller
As alluded to by Slicedpan
, I would get rid of any direct outputs (puts) from the controller.
You should use this:
#app/controllers/perforce_sync_controller.rb
def getPerforce
respond_to do |format|
format.html { @return = "Called getPerforce" }
format.js { @return = "hi" }
end
end
#app/views/perforce_sync/getPerforce.js.erb
alert("<%=j @return %>");
Upvotes: 1
Reputation: 5015
This is due to the way rails responds to controller actions. By default, if you don't call render
in the controller action, then it will look in your views folder for a template. That's why it wanted you to create a getPerforce.erb.html
file.
To make it just return plain text, in the controller you can write:
render :text => 'Hi!'
If you are doing AJAX stuff, then typically you will want to return JSON, you can also do this in the controller like so
render :json => {:data_key => 'A value'}
Upvotes: 3