Last active
July 12, 2016 19:28
-
-
Save kumarabinash/351ce825fec48e102aa3c6330aaa11dd to your computer and use it in GitHub Desktop.
Answer for http://stackoverflow.com/questions/38335562/rails-trouble-sending-ajax-data-to-controller/38335726
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div id="wrapper"> | |
<div id="menu"> | |
<p class="welcome">Welcome, <b></b></p> | |
<p class="logout"><a id="exit" href="#">Exit Chat</a></p> | |
<div style="clear:both"></div> | |
</div> | |
<div id="chatbox"></div> | |
<form id="frm1" action=""> | |
Message: <input type="text" name="fname" value="Donald"><br> | |
<!-- <input type="submit" value="Submit"> --> | |
</form> | |
<button name="submitmsg" type="submit" id="submitmsg" value="Send">Try it</button> | |
</div> | |
<p id="demo"></p> | |
<script> | |
$(document).ready(function(){ | |
$("#submitmsg").on('click', function(e){ | |
e.preventDefault(); | |
var x = document.getElementById("frm1"); //This is the form, and not the value of the textbox | |
var text = ""; | |
var i; | |
for (i = 0; i < x.length ;i++) { | |
text += x.elements[i].value + "<br>"; | |
} | |
document.getElementById("chatbox").innerHTML += text; | |
//Actual message is in 'text' | |
$.ajax({ | |
url: "/messages", | |
method: "post", | |
data: { data_value: text }, | |
dataType: "JSON", | |
success: function(response){ | |
//do something,maybe notify user successfully posted their message | |
}, | |
error: function(error){ | |
console.log(error); | |
} | |
}); | |
}); | |
}); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Attr</title> | |
<%= csrf_meta_tags %> | |
<%= javascript_include_tag "application" %> | |
</head> | |
<body> | |
<%= yield %> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def create | |
# debugger | |
@message = Message.new(message_params) | |
respond_to do |format| | |
if @message.save | |
format.html { redirect_to @message, notice: 'Message was successfully created.' } | |
format.json { render :show, status: :created, location: @message } | |
else | |
format.html { render :new } | |
format.json { render json: @message.errors, status: :unprocessable_entity } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment