Reputation: 33
I am working on Rails and having problem with ajax post data call. It is working and data is entered in db but the SUCCESS function is not working, as alert function in success function is not firing.
Further I want to add comment to my post without refreshing whole page.
AJAX code looks like :
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '/comments/create',
type: "POST",
dataType: 'json',
processData: false,
success: function (msg) {
alert(msg);
},
error: function (xhr, status) {
alert(xhr.error);
}
});
});
});
</script>
and Controller code is :
def create
puts 'params', params.inspect
@post = Post.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
respond_to do |format|
if @comment.save
format.html { redirect_to(@post, :notice => 'Thanks for comment.') }
format.json { render json => @post, :msg=>"comment oK" }
else
format.html { render :action => "new" }
format.json { render :xml => @comment.errors, :msg=>"comment oooK", :status => :unprocessable_entity }
end
end
end
This code works fine to post the data to the create function, which creates (posts?) the entry to the db. But I would like to return the data in the alert function upon "success" but alert in success function is not working and alert in error function is firing.
Upvotes: 1
Views: 3387
Reputation: 1892
Try:
$('form').submit(function()
{
var myForm = $('form').serialize();
$.ajax
({
url:'/comments/create',
type:"POST",
dataType:'json',
data: myForm,
processData:false,
success: function (msg)
{
alert(msg);
},
error: function (xhr, status)
{
alert(xhr.error);
}
});
});
If this doesn't work, please write what you're sending across the wire in your AJAX request. Use Chrome Console or Firebug to check and paste the POST results in here.
Upvotes: 1