18433

jQuery call to controller action is not as expected

Question:

I have the following <strong>jQuery</strong>:

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 <strong>routes.rb</strong>:

get "getPerforceSuites", to: "perforce_sync#getPerforce"

and in my <strong>perforce_sync_controller.rb</strong>:

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!

Answer1:

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'}

Answer2:

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

<hr />

<strong>HTML</strong>

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

<hr />

<strong>Controller</strong>

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 %>");

Recommend

  • Conflict between Facebook Sign In and Google Sign In - iOS
  • Erratic data cursor behavior for triangulated 3d surfaces in MATLAB R2011b
  • Using c2hs on Windows
  • How does Skobbler prioritize which POIs to show?
  • Measure heap used by each object in Java [closed]
  • Counting Treaps
  • F#: In which memory area is the continuation stored: stack or heap?
  • Getting NullPointer exception with File.listfiles()
  • saving file generated by TCPDF
  • How to view images from protected folder with php?
  • Debug.DrawLine not showing in the GameView
  • Textfile Structure (tables)
  • How do I get HTML corresponding to current DOM tree?
  • JQuery Internet Explorer and ajaxstop
  • JSON response opens as a file, but I can't access it with JavaScript
  • R - Combining Columns to String Based on Logical Match
  • Read text file and split every line in MSBuild
  • C# - Serializing and deserializing static member
  • Java applet as stand-alone Windows application?
  • javascript inside java/jsp code
  • Sending data from AppleScript to FileMaker records
  • vba code to select only visible cells in specific column except heading
  • Change an a tag attribute in JavaScript based on screen width
  • Why winpcap requires both .lib and .dll to run?
  • Return words with double consecutive letters
  • how to add data labels for bar graph in matlab
  • How to get icons for entities from eclipse?
  • KeystoneJS: Relationships in Admin UI not updating
  • AngularJs get employee from factory
  • Proper way to use connect-multiparty with express.js?
  • Load html files in TinyMce
  • Error creating VM instance in Google Compute Engine
  • How to set the response of a form post action to a iframe source?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • unknown Exception android
  • JaxB to read class hierarchy
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal