Quinty
Quinty

Reputation: 199

How can I change the view from a rails controller after a post?

I'm new to jQuery/Javascript and I'm having trouble implementing a chat room with a robot. I'm particularly stuck on the communication b/w the controller and JS.

Basic functionality:

  1. User types comment
  2. Javascript sends post to rails controller with comment data
  3. Ruby class (@bot) takes the comment and returns a response
  4. Response gets added to view

    Here is what I have so far

Controller

class MainPageController < ApplicationController
  def chat
    @username = params[:username]
    @bot = JibunBots.new(@username, Message.where(:username => @username).first.message)
    respond_to |post| do
       return @bot.conversation(post.data)
    end
  end
end

Javascript

$(document).ready(function () {

$("#submitmsg").click(function(){   

    var clientmsg = $("#usermsg").val();
    $('<p>' + gon.username + ":  " + clientmsg + '</p><br>').appendTo('#chatbox');  
    $("#usermsg").attr("value", "");
    #SEND POST HERE?
    #RECEIVE DATA FROM CONTROLLER?
    #ADD NEW COMMENT HERE?
    });
    })

Upvotes: 1

Views: 126

Answers (1)

Leo Van Deuren
Leo Van Deuren

Reputation: 435

You have the basic structure idea correct. You just need to send a post request to a route you have create in routes.rb related to your controller and return a json object with the message you saved.

jQuery.ajax({
  url: "/chat/create", // a route in routes.rb for your controller
  type: "POST",
  data: {comment: submitted_comment , user_id: user_id }, // place to send data to your controller
  dataType: "json"
  success: function(data){
     // data will be the response object(json)
     // use data to create new chat object using a template of some sort
  }
});

Upvotes: 1

Related Questions