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?
I’m assuming here that by something not being processed as AJAX that you mean that it’s not rendering the
view.js.erbfile, but rather theview.html.erbfile instead. You can fix this by forcing the format of the URL in your JS like this:That would then send it to the right format for your action.