Kendall Weihe Kendall Weihe - 3 months ago 4x
Ruby Question

Rails trouble sending AJAX data to controller

I'm a AJAX rookie, so bear with me. I'm trying to send data from a chat-message box to two places -- the actual chat box and to a rails method. That way I can display the meesage, and also store the message in my DB.

I have the following JS/HTML code

<button onclick="myFunction()" name="submitmsg" type="submit" id="submitmsg" value="Send">Try it</button>

function myFunction() {
var x = document.getElementById("frm1");
var text = "";
var i;
for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
document.getElementById("chatbox").innerHTML += text;

url : "/messages/create",
type : "post",
data : { data_value: x }
dataType : "text" //this might be wrong?


I can successfully insert into the HTML DOM, but it isn't sending the data to the messages controller
action. My messages controllers is named
and the action is

I've added
in my
action in order to then view what
are, but it never even executes the code.

Some routes:

messages GET /messages(.:format) messages#index
POST /messages(.:format) messages#create
new_message GET /messages/new(.:format) messages#new
edit_message GET /messages/:id/edit(.:format) messages#edit
message GET /messages/:id(.:format) messages#show
PATCH /messages/:id(.:format) messages#update
PUT /messages/:id(.:format) messages#update
DELETE /messages/:id(.:format) messages#destroy


wait, something is wrong with my JS code. It was previously inserting HTML into the DOM, but somewhere along adjustments it stopped. Now the console is throwing the error
new:110 Uncaught SyntaxError: Unexpected identifier
line 110 is commented out.

When I the
call out of the function, then it works fine. I have something syntactically wrong when I call the
function inside

  url : "/messages", //by rails convention doing a post simply to '/messages' should be handled by create action
  method : "post",
  data : { data_value: x },
  dataType : "json", //this might be wrong?
  success: function(response){
    //do something,maybe notify user successfully posted their message
  error: function(error){

And in your create method you should handle json requests

def create
  //save message!
  respond_to do |format|
    format.json { json: @message.as_json }

This is how your code should look like. You can always do more creatively.

Please checkout this gist