0

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()

Kendall Weihe
  • 2,021
  • 4
  • 27
  • 53
  • What routes have you defined? Can you add codes for `create` method in your controller? – Kumar Jul 12 '16 at 17:39
  • You're correct in your guess, `dataType` should be `json`. – Nic Nilov Jul 12 '16 at 17:39
  • @NicNilov that didn't resolve the issue. Am I correct in that if I place `debugger` in the `create` action, then it should open the debugger in the console? I have added routes – Kendall Weihe Jul 12 '16 at 17:41
  • Depending on your setup, this is what might happen. Another option is using `binding.pry`. As @Kumar proposed you should add your routes to the question. – Nic Nilov Jul 12 '16 at 17:42
  • @Kumar I added `rake routes` there is no point in posting my `create` code because I haven't got that far. I want to verify data is being passed via `params` first by adding `debugger` in the `create` action -- and then verifying in the interactive ruby debugger. – Kendall Weihe Jul 12 '16 at 17:43
  • Your routes look fine. Try changing `type: 'post'` to `method: 'post'`. Also, do you see any errors in browser console? – Nic Nilov Jul 12 '16 at 17:45

1 Answers1

1
$.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

Kumar
  • 3,116
  • 2
  • 16
  • 24
  • `create` still isn't being executed -- verified by placing `debugger` as the first line in the `create` action – Kendall Weihe Jul 12 '16 at 17:47
  • Did you pick up the `url : "/messages"` change? – Nic Nilov Jul 12 '16 at 17:47
  • Yes, please check update. something is wrong in my JS code now. Sorry, trying to multitask here... let me try some things – Kendall Weihe Jul 12 '16 at 17:50
  • what's there in line 110? – Kumar Jul 12 '16 at 17:54
  • please check the update -- I have something wrong when I call the `.ajax` function inside `myFunction()`. If I take the `.ajax` call out of the function, then the HTML insertion works fine, but when I add the `.ajax` call back it stops the insertion from working. do you think this is a rails issue? – Kendall Weihe Jul 12 '16 at 17:55
  • One you're missing a comma after, `data : { data_value: x }`. Everything else seems to be fine. Can you update that and let me know if everything works? – Kumar Jul 12 '16 at 17:58
  • the comma was the issue, now HTML insertion works. Now it's throwing error `new:106 Uncaught ReferenceError: $ is not defined` line 106 is the ending of the ajax call `});` – Kendall Weihe Jul 12 '16 at 18:02
  • That's jquery. Are you loading jquery? Please verify that in your `application.js` file – Kumar Jul 12 '16 at 18:03
  • `//= require jquery //= require jquery_ujs //= require_tree .` I'm missing turbolinks because of this: http://stackoverflow.com/questions/38274500/embedded-google-maps-in-rails-not-responsive?noredirect=1#comment63968495_38274500 – Kendall Weihe Jul 12 '16 at 18:04
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117126/discussion-between-kumar-and-kendall-weihe). – Kumar Jul 12 '16 at 18:05