Take the 2-minute tour ×

So I have an autocomplete field where a user can select an existing or create a new tag. If a user creates a new tag, he presses the form button, and it sends a POST request to the update action in the videos controller which processes the request as AJAX, and the tag gets displayed above the field.

Now, the problem is when a user selects a tag from the suggestion list. By default, the jQuery UI autocomplete plugin appends the selected element inside the field, and then the user has to press the form button. However, I want to save the user some effort by automatically adding the tag right when it's picked from the suggested list. Therefore, I have this code in my application.js file:

select: function(event, ui) {
           var url = $('.edit_video').attr('action');
           var val = ui.item.topic.name;
           $.ajax({type:"PUT", url:url, data:{video:{topic_names:val}}});
           return false;

That successfully sends a PUT request to the update action when an element is selected from the list. However, the request is NOT processed as AJAX. The tag is successfully added, but only after a page refresh. I want the request to be processed as AJAX. How can I do this?

I'm guessing that the problem has to do with the fact that when you press the form button, the :remote => true option tells rails to look for format.js (which I have in my update action), but when the button is not pressed, and an element is selected from the list, Rails does not know to look for JS. How do I let it know?

share|improve this question

4 Answers 4

up vote 0 down vote accepted

I'm assuming here that by something not being processed as AJAX that you mean that it's not rendering the view.js.erb file, but rather the view.html.erb file instead. You can fix this by forcing the format of the URL in your JS like this:

var url = $('.edit_video').attr('action') + ".js";

That would then send it to the right format for your action.

share|improve this answer

Using dataType: 'script' in your Ajax request should help.

$.ajax({type:"PUT", url:url, dataType: 'script', data:{video:{topic_names:val}}});

This will add the correct headers to have rails recognize the correct answer format.

share|improve this answer

'protect_from_forgery' might be stopping you from the post. you may check it with firebug (with firefox)



share|improve this answer

I'd check to see if anything else is binded to $('.edit_video') in firefox. You might be submitting the form.

Also JS could be disabled on the browser so it will degrade to non-ajax.

Finally check that you have the jQuery and <%= csrf_meta_tag %> in the layout file. Good luck.

share|improve this answer

Your Answer


