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

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

Related

keys and values from an ajax POST are all escaped

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.

Custom post using angular rails resource

Hi I'm using rails and angularjs with the angularrailsresource gem. I need to do a custom post request to a rails resource I have defined called 'Comment'. I tried using the $post method like this:
Comment.$post('some_method', {comment_id: comment.id, username: username, type: 'mention'}).then(function(result){
console.log(result);
});
and it makes a request but it always makes it under the root of the page I'm on. So I want to make a request to '/comments/', but it tries to make a request to '/patients/some_method' and if I do this:
Comment.$post('comments/do_stuff', {comment_id: comment.id, username: username, type: 'mention'}).then(function(result){
console.log(result);
});
it will try to post to 'patients/comments/some_method', or whatever else the root of the page I'm on is. Is there a way to tell it to post directly to the resource and not through the the url context that I am currently on? Thank you for your help.
You have to use the path with a / before it, otherwise it will trigger the action using the relative path. Try this:
Comment.$post('/comments/do_stuff' ....
Notice the / before comments.

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