开发者

Send parameters to rails app using jQuery

I'd like to send variables from my form to my rails app using jQuery, is this possible, currently I have the code below, and set my rails app to get the parameters which are then inserted into a db.

What am I doing wrong?

var dataString = 'author='+ name + '&book=' + book + '&genre=' + genre;

$.ajax({
type: "POST",
url: "http://localhost:3000/books",
data: dataString,
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h2>Book Submitted!</h2>")
.append("<p>You will be notified soon!</p>")
.hide()
.fadeIn(1500, function开发者_StackOverflow() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});

Thanks


If you are passing parameters from another application (Rails, HTML, PHP or otherwise) then the issue is probably that Rails is expecting that you pass an authenticity token. Since you can't use one (because you are passing data from another application) you'll need to do one of the following.

For specific actions, don't protect from forgery:

protect_from_forgery :except => [:create, :update]

Or for an entire controller:

skip_before_filter :verify_authenticity_token


Try to use token in your query. This is protection from XSS-attacks.

'authenticity_token': AUTH_TOKEN

for example:

var dataString = 'author='+ name + '&book=' + book + '&genre=' + genre + '&authenticity_token='+AUTH_TOKEN;


The absolute path in your URL parameter is arousing my suspicions.

Ajax calls can only be made to the same server the page is served on due to javascript's same origin policy.

Is your html page also hosted on http://localhost:3000? If not that is your problem.

If it is then look at the answers about authenticity tokens.


I don't think you need jQuery to pass parameters from a form in Rails app.

Normally command rails generate scaffold generates views for editing and creating a new resource. These views contain forms that pass parameters to database with no jQuery.

Here is a nice tutorial http://railstutorial.org/chapters/a-demo-app#top

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜