The jquery-rails gem contains all 3 jQuery versions. You can use jQuery 1, 2, and 3 by requiring jquery, jquery2, and jquery3 on application.
The directory structure for JavaScript has changed to the app/javascript/packs/ folder. In that folder you will find the application. js file, which is just like the application.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
PUT and DELETE are not supported by all browsers, RubyOnRails supports passing an extra parameter with your data called _method which will indicate how RoR will treat the request.
$.ajax({
type: "POST",
url: '/admin/pages/1.json',
data: { _method:'PUT', page : {...} },
dataType: 'json',
success: function(msg) {
alert( "Data Saved: " + msg );
}
});
The dataType
param in jQuery isn't what you send, but rather specifies the format you expect the answer to be (yes, that's a very poor name). If you want to send your data to the server in a format other then application/x-www-form-urlencoded
you should use contentType
param. You also need to serialize your data
:
$.ajax({
type: "PUT",
url: '/admin/pages/1.json',
data: JSON.stringify({...}),
contentType: 'application/json', // format of request payload
dataType: 'json', // format of the response
success: function(msg) {
alert( "Data Saved: " + msg );
}
});
Ok, actually my JSON data didn't have the page key, my mistake. So thats why it was not correctly parsing. But now I get "[object Object]" string as the value for page key instead of a nicely parsed json object.
Where should I look: JQuery or Rails?
EDIT:
I've solved my issue stringifying the json object with a script found here: www.json.org/js.html:
$.ajax({
type: "PUT",
url: '/admin/pages/1.json',
data: { page : JSON.stringify( {...} ) },
dataType: 'json',
success: function(msg) {
alert( "Data Saved: " + msg );
}
});
On the rails side json gem must be required. In the controller:
params[:page] = JSON.parse params[:page] if params[:page].is_a? String
var id = $('#route_id').val()
$.ajax({
type: 'PUT',
url: '/routes/'+ id,
data: $('#markerform').serializeArray(),
dataType: "JSON",
success: function(data) {
console.log(data);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With