I want to do the following: The client (from a different domain, right now a JQuery-Script on my local computer) sends a Ajax-Post to the server, the server saves the result to the server and sends HTML/text back to the client who injects it into his HTML.
This is the Ajax-Call:
var params = '{"comment": "Test", "creator": "Prof Frick", "name": "Rainer", "url": "' + url + '"}';
alert(params);
$.ajax({
type: "post",
data: params,
url: 'http://localhost:3000/pages/postjson/',
success: function(data) {
$('h1').html(data);
}
});
});
This is my route:
match '/pages/postjson/' => 'pages#postjson'
And this is the controller:
def postjson
parsed_json = ActiveSupport::JSON.decode(request.body.read) #
@page = Page.where(:url => parsed_json["url"])
new_obj = Page.new
new_obj.name = parsed_json["name"]
new_obj.creator = parsed_json["creator"]
new_obj.url = parsed_json["url"]
new_obj.comment = parsed_json["comment"]
new_obj.save
render :json => @page[:name]
end
I think my mistake is be quite basic and I really appreciate your help. My guess is that the mistake is either in
@page = Page.where(:url => parsed_json["url"])
or in
render :json => @page[:name]
because everything goes through, the json-data gets saved, the browser even alerts “Success”, but the I want to post to just disappears.
Thanks for your advice. General coding tips also always appreciated!
I finally solved the puzzle (for me):
After reading a lot I found this tutorial
I changed my controller to look similar to this:
And my JQuery-Function looks like this:
So happy that it is finally working 🙂