开发者

Jquery Ajax Function Problems

I need some help with my jquery which should complete a task in our Rails3 application. Thanks to others on here, I have a checkbox which when clicked, is supposed to mark a task's status as completed.

In my rails code, I have this;

<%= check_box_tag 'complete_task_1', '', false, { 'href' => completed_task_path(task.id) } %>

In my application.js, I started with this:

 $('#complete_task_1').click(function() {
  $.ajax({
    url: $(this).data('href'),
    type: 'post',
    dataType: 'html',
    success: function(data, textStatus, jqXHR) {
        $('#thing').css("color","red");
        alert ('yabadabadoo');
    }
  });
});

This gives me an error though - no route matches for /tasks

To test, I replaced the url with:

tasks/4/complete

Which toggled the status in the db but did not refresh on the page. I therefore have two questions:

  1. What's wrong with the url / function above?
  2. What can I include so that the task disappears from page without reload?

-- UPDATE --

Tried using code as per @darin-dimitrov suggestion below and I get logged out of my application... The 开发者_如何学编程error shown in development log is:

Started POST "/tasks" for 127.0.0.1 at 2011-07-16 13:27:32 +0100
  Processing by TasksController#create as HTML
  SQL (143.6ms)  describe `roles_users`
  User Load (0.5ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
  SQL (0.2ms)  BEGIN
  SQL (0.6ms)  COMMIT
Completed   in 454ms

Looks like it's not getting the right url still. Should I be using POST as well?


Try this:

{ 'data-href' => completed_task_path(task.id) }

and then:

url: $(this).data('href')

should give the correct url (tasks/4/complete).

Or if you dont use the data- prefix you could use this:

url: $(this).attr('href')

but as href is not valid attribute on a checkbox the firstr solution seems better.


First note very carefully that $().data() is different from $().attr().

Read this article for more.

On the ruby side you are probably adding an href attribute to the checkbox -- right? (i am not into ruby)

Don't try to access an attribute with $().data() -- that is NOT correct.

First try to hard code the URL in the url property and see if it works. If yes -- then it is simply the problem that you are not able to access the href on the checkbox. Try $().attr().

You could also use a rel attribute instead of href -- that's a standard attribute on checkboxes. But href should do also.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜