I have a JavaScript app that produces a string. I want to transfer this string back to my server and assign it to a particular attribute. Apparently AJAX can accomplish this. Unfortunately, I’m a novice with both Rails and AJAX, and I can’t find any clear instructions on how to implement the transfer. Is there a simple, standard way to send a string to a Rails server and assign it to a model attribute?
At the moment, the code is inserted directly in my JavaScript function. It looks like this:
$.ajax({
type: 'POST',
url: '/bookcases/'+window.location.href.split('/')[4],
data: {'_method':'put', 'bookcase[imagemap]':mapcode},
dataType: 'html',
success: function() {alert( "Data Saved" );}
});
Firebug gives me a 404 Not Found error. I’ve tinkered with the URL a bit, replacing ‘edit’ with likely candidates like the name of the attribute and POST. I’ve also removed ‘edit’ all together. So far I consistently get the same error. The only exception is when I set the URL to ‘/’, at which point the success message pops up. Unfortunately, the mapcode data has not actually been implanted.
Got it! Apparently, the above code was working just fine. I just needed to add an update method to my controller. For those working through a similar issue, Firefox’s Firebug is invaluable. If you’re encountering an error in JavaScript, Firebug will show you what the cause is. I couldn’t have figured this out without it.