Kendall Weihe Kendall Weihe - 4 months ago 19
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>

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

$.ajax({
url : "/messages/create",
type : "post",
data : { data_value: x }
dataType : "text" //this might be wrong?
});

}
</script>


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

I've added
debugger
in my
create
action in order to then view what
params
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


UPDATE

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
.ajax
call out of the function, then it works fine. I have something syntactically wrong when I call the
.ajax
function inside
myFunction()

Answer
$.ajax({
  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){
    console.log(error);
  }
});

And in your create method you should handle json requests

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

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

Please checkout this gist