Reputation: 199
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:
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
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