keys and values from an ajax POST are all escaped - ruby-on-rails

I am trying to access some params from an ajax post in Rails. But my params are all escaped. I am not quite whether this is the best way to go about it. If I inspect the params[:event] vairable in Rails I end up receiving it looks something like this
{\"title\":\"None\",\"startdate\":\"2014-01-23\",\"enddate\":\"None\",\"description\":\" Description\"}
I am sure I can use this data if I really wanted to. But is this really the best way to receive data on my backend?
For reference, ajax
$.ajax ({
type: 'POST',
url: '/api/calendar',
dataType: 'json',
data: {'event': JSON.stringify(this)},
success: function(response) {
console.log('Success ', response);
}
});
Typical data
event:{
"title":"None",
"startdate":"2014-01-23",
"enddate":"None",
"description":"Description"
}
Two questions:
Is this the only way rails would accept data?
If this is the safest way to post data to my backend what would be the easiest way of accessing the data?
Any help would be appreciated, thank you

The JSON.stringify was the culprit. I was using a backbone model and switched to .toJSON instead.

Related

Best way to send javascript variables to ERB in rails using ajax?

I know you can use ajax, but I cant figure out how... It's really frustrating. Can anyone help?
Sample ajax call
$.ajax({
url: '/home/index',
data: {params1: "", params2: ""},
success: function(response) {
// code to be executed
}
});
In rails HomeController index action
you can get your parameters , then by assigning those params to an instance varible, you can get those values in your ERB file

How do I pass multiple objects to the Rails controller action "create" via JSON?

As you can probably tell by this question, I am a newbie to both Ruby on Rails and Knockout.
I'm trying to build a RoR web app that will allow a user to pull up their assets data which is stored in a MySQL database, edit that data using Knockout on the front end, and then use Knockout to send the revised data back to the server via Ajax to Rails.
At this URL here: http://knockoutjs.com/documentation/observableArrays.html
it says:
The convention in Rails is that, when you pass into an action a JSON object
graph, the framework can automatically convert it to an ActiveRecord object
graph and then save it to your database. It knows which of the objects are
already in your database, and issues the correct INSERT or UPDATE statements.
I've tried doing Google searches and I haven't found anything that makes it clear to a newbie like myself. So I'm asking this question here.
In Knockout.js, when the user submits, they will be triggering a function "saveAssets" which will send the data in JSON format to "/assets" on the Rails app. The idea is that "self.assets()" will contain multiple instances of Asset objects.
self.saveAssets = function() {
$.ajax('/assets', {
data: ko.toJSON({ assets: self.assets() }),
type: "post",
contentType: "application/json",
success: function() { console.log('hella') }
});
};
When that function executes, here is the JSON that gets posted to the Rails server. Most of the Asset objects have id values, which means they are already in the server and I just want to update them, but there's also one new Asset record without an id number:
{"assets": [
{"id":1,"desc":"DWS Investments Roth IRA Mutual Fund","shares":"810.577","symbol":"SCQGX","price":"41.17","total":"33371.46"},
{"id":2,"desc":"DWS Investments Money Market Fund","shares":"20000.00","symbol":null,"price":1,"total":"20000.00"},
{"id":6,"desc":"credit card debt","shares":"-8700.00","symbol":null,"price":1,"total":"-8700.00","_destroy":true},
{"shares":"0.00","symbol":"","price":1,"total":"0.00"}
]}
And here's the Ruby on Rails controller action code:
def create
respond_to do |format|
format.json {
#assets = params[:assets]
#assets.each do |this_asset|
#a = Asset.new(this_asset)
#a.save
end
}
end
end
What am I supposed to be doing in the "create" action in order to receive the JSON array, parse it into individual "Asset" objects and save/update them to the database?
Thanks for your help!

Rails: Pass Params Through Ajax

I need to pass params through javascript back to the server. At the moment, I pass them into javascript like so:
sendParams("<%= params[:q].to_json %>");
And then send them back like this:
function sendParams(q){
$.ajax({
url: '/mymodel/myaction',
type: 'post',
data: {'q':q},
contentType: 'json'
});
}
In my controller, I try to use them like I would any other params:
MyModel.where(params[:q])
But the params are coming back empty, even though firebug shows this in the POST tab:
q=%7B%26quot%3Bc%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Ba%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bname%26quot%3B%3A%26quot%3Btitle%26quot%3B%7D%7D%2C%26quot%3Bp%26quot%3B%3A%26quot%3Bcont%26quot%3B%2C%26quot%3Bv%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bvalue%26quot%3B%3A%26quot%3B2%26quot%3B%7D%7D%7D%7D%2C%26quot%3Bs%26quot%3B%3A%7B%26quot%3B0%26quot%3B%3A%7B%26quot%3Bname%26quot%3B%3A%26quot%3Bvotes_popularity%26quot%3B%2C%26quot%3Bdir%26quot%3B%3A%26quot%3Bdesc%26quot%3B%7D%7D%7D
Any idea why this information isn't getting processed by the where clause? What can I do to make the params Rails readable again?
UPDATE:
Started POST "/publications/search?scroll=active&page=6" for 127.0.0.1 at 2013-0
2-12 22:55:24 -0600
Processing by PublicationsController#index as */*
Parameters: {"scroll"=>"active", "page"=>"6"}
UPDATE 2:
The problem is apparently stemming from contentType. When I remove it, then q is sent as a Rails parameter. Unfortunately, q is still in JSON, resulting in the error:
undefined method `with_indifferent_access' for #<String:0x686d0a8>
How can I convert JSON to a params hash?
Your data parameter is wrong.
You have
data: {'q':q},
It should be
data: {q: 'q'},
There were a couple of issues that needed to be resolved for this to work. First, q wasn't being sent as a parameter to Rails, even though it was posting. The reason was because it was being treated as JSON data rather than as a parameter. I fixed this by removing the line:
contentType: 'json'
After that, the AJAX properly sent 'q', but Rails had trouble using it as it was in JSON. I had to parse it with ActiveSupport::JSON.decode, but this was throwing a 737: unexpected token error. I ran the code through (JSONlint)[http://jsonlint.com/], and it turns out that all the quotation marks had been escaped.
From there, there were two solutions. The obvious one was to use .html_safe like so:
sendParams("<%= params[:q].to_json.html_safe %>");
But this caused problems when the user inputed quotes. The safer alternative was to decode the escaped HTML entities after they were passed back to Rails like so:
ActiveSupport::JSON.decode(CGI.unescapeHTML(params[:q]))
And this did the trick.

Rails session doesn't saved during ajax call

I have this ajax call after completing specific action
$.ajax({
type: "POST",
url: $("#myform").prop('action'),
data: $("#myform").serialize(),
xhrFields: {withCredentials: true},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').last().attr('content'));
}
});
this ajax call refering to create action, so I wanna save the params of the form in the session I've created before. so I put this in create action
def create
session[:my_session].deep_merge!(params[:user])
puts session[:my_session]
I print the session to make sure from the server that it contains the right params, and Yeah, it has been printed with the right values.
{"profile_id"=>"1000", "first_name"=>"john", "last_name"=>"vieira", "email"=> "john#sandsora.com"}
the problem here is after that call, the session doesn't save the data which I've stored!, which means that it stored the latest data before this assignment. I searched for that error and I got that it may be CSRF token error and I fixed it by adding beforeSend function, but I still have the same problem, so any suggestions please?
My first guess would be that the session cookie headers are not being set. Without this cookie rails has not way of setting the correct session and you data is "lost" after the request has completed. Your browser should send it automatically on your ajax requests though...
Can you verify that the session cookie is being sent with your ajax request?

ajaxSetup not working with Rails / jquery-ujs

I'm working on a project that makes heavy usage of XHR, and there is some data that needs to be appended to each ajax request in order for the server side to properly keep track of what is going on in the browser.
I have a generic class called xhr_response_handler than I use to handle the callbacks for all ajax requests that is added to all forms, links etc that is making ajax requests. (i.e. where ":remote => true" in rails)
$('.xhr_response_handler')
.on('ajax:success', function(event, data, status, xhr) { xhr_success(data); })
.on('ajax:failure', function(xhr, status, error) { xhr_fail(error); });
Then I try to append the default data sent with each request using:
$.ajaxSetup({
data: {
Foo: <%= #Bar %>
}
});
This works for some of the elements where the ajax settings are configured directly with jquery, but this does not work for some elements created using rails methods like link_to and form_for with :remote => true.
The odd thing is that if I also add
$('.xhr_response_handler').data( 'params', { Foo2: <%= #Bar2 %> } );
Then that works for adding data to the rails generated ajax requests using link_to. What makes it odd is that now all of a sudden the ajaxSettings also works, and in the ajax requests I get both Foo and Foo2 as parameters. But I get no parameters at all when using ajaxSettings by itself.
Furthermore, none of the data to be appended gets serialized into the form data sent in ajax requests generated from the rails form_for method.
Any help would be appreciated.
Rails 3.2.3
Ruby 1.9.3p194
jQuery 1.7.2
I think this behaviour appears because the data hash of $.ajaxSetup is overridden by the ajax calls you do later on. The data has to be merged manually.

Resources