I'm wanting to check a ruby session variable via ajax. I'm familiar with ajax calling php, is calling a ruby file similar?
I'm talking about a 'session[:var_name]' type variable in a Rails environment using JQuery.
Something like:
$.ajax({
url: path to ruby file,
type: "GET",
dataType: "html",
success: function(html){
...
AJAX requests are not that different from other requests. You might need to change your return type based on what kind of AJAX request you make. If your Javascript is expecting text you can just write an action in a controller like this:
def your_ajax_action
render :text => session[:var_name].to_s
end
If your Javascript is expecting XML, you need to generate the XML then have an action in your controller like this:
def your_ajax_action
render :xml => {:var_name => session[:var_name]}.to_xml
end
Or, if you expect JSON:
def your_ajax_action
render :json => {:var_name => session[:var_name]}.to_json
end
Related
I'm trying to use strong parameters via ajax call and I get NoMethodError (undefined method 'permit' for ...) with the codes below:
ajax call
onSubmit(value) {
const url = '/tweets/create';
$.ajax({
url: url,
dataType: 'text',
type: 'POST',
cache: false,
data: {
tweet: value
},
success: (data) => {
// whatever
},
error: (xhr, status, err) => {
console.error(url, status, err.toString());
},
});
}
tweets_controller.rb
def create
tweet = Tweet.new(create_params)
tweet.save
end
private
def create_params
params.require(:tweet).permit(:tweet)
end
tweet.rb
belongs_to :user
validates :tweet, { presence: true }
However, it works fine if I don't use strong parameters with the same ajax call like below:
def create
tweet = Tweet.new(tweet: params[:tweet])
tweet.save
end
How can I make it to work with strong parameters?
I wonder if the problem is that the argument for the permit function should be one or more (or an array) of scalar values, and not an object? According the the Git Hub documentation,
To whitelist an entire hash of parameters, the permit! method can be used
params.require(:log_entry).permit!
You could try
params.require(:tweet).permit!
if you haven't already, and see if that fixes it. Otherwise, there is lots of documentation on the link above which might help. If you are still stuck, try posting the code from your tweets.rb file above as well so others can test.
I need to render a Flask template but the ajax data is only accessible within the POST if statement and does not show when I call a get direct after a posted the data.
I have a working ajax here
$.ajax({
type: 'post',
url: "/query",
dataType: 'text',
data: JSON.stringify({hostname:hostname, bf_id:computerID}),
contentType: 'application/json;charset=UTF-8',
success: function () {
window.location.href = "/query";
}
});
});
The data is successfully posted and the redirect is working. But when the redirect calls the function to render the template, the posted ajax cannot be retrieved.
#app.route('/query', methods=["GET", "POST"])
def query():
hostname=""
if request.method == "POST":
#these values only exist in if statement
hostname = request.json['hostname']
bf_id = request.json['bf_id']
return render_template('query.html', hostname=hostname)
Am I using an incorrect work flow?
Am I using an incorrect work flow?
Yes.
You make the POST request with the data.
You get a response which does things with that data
You then make a GET request without the data
You get a response which can't do things with the data that it doesn't have
The point of Ajax is to make an HTTP request without loading a whole new page.
If you want to load a whole new page, then use a regular form submission without involving JavaScript at all.
I have a simple setup for a resource, currently in routes.rb I have:
resources :leave_requests
This works exactly as expected, on the index view I have a datatable setup using Ajax via a GET, this is also working but the URI is getting very large during the Ajax request. I would prefer this to be a POST action, for this to work I require a POST instead of a GET on the index action in my routes.
However, this will break the CREATE action i.e. will simply load the index page on submitting a new request. i.e. If I do this:
post '/leave_requests', to: 'leave_requests#index'
resources :leave_requests
How can I get these to co-exist happily?
Have you try to do something like in this Rails , Ajax , Post Function , Jquery the code looks something like
$('form').submit(function()
{
var myForm = $('form').serialize();
$.ajax
({
url:'/leave_request/create',
type:"POST",
dataType:'json',
data: myForm,
processData:false,
success: function (msg)
{
alert(msg);
},
error: function (xhr, status)
{
alert(xhr.error);
}
});
});
you can also take a look at jQuery post to Rails
I am trying to attach data to my requestbody while sendign using jQuery ajax.
If I tried to do it using the extension RESTCLient is either firefox or chrome it works fine, which means that my method on the serverside is working fine.
That is why I am pretty sure that it the ajax call I am making
$.ajax({
url: 'lingosnacks/delete/'+ id,
type: 'POST',
data: $('#email').val() + $('#password').val()
dataType: "json",
success: function(data) {
console.log("FILL| Sucess| ");
console.log("FILL| Sucess| Data| " + data);
fill(data);
}
});
The data line is wrong, it should be very similar to a JSON string, like this:
data: {email: $('#email').val(), password: $('#password').val()},
You need to have the data you are sending in this format:
email=blah%40blah.com&password=pass123
You can do that with jQuery using $('form').serialize()
Also, you are missing a , after your data string in the Ajax call.
Actually data param in jQuery Ajax method is for sending url params.
You can send the same by appending then into the url but to make the code more readable e and organized i would prefer to use data variable.
So your data content should look like :
data : "email="+$('#email').val()+"&password="+$('#password').val();
I am not pretty sure if sending params like a json object will work or not because i never used it.
I have a controller action (lets call it some_controller_action) that needs to render out some json (for the javascript to pick up) and at the same time refresh/re-render a partial using some_controller_action.js.erb.
My code suggestion is something like this:
def some_controller_action
#
# lots of code here
#
respond_to do |format|
render :json => {:something => something}, :status => :ok
format.html {
redirect_to somewhere
}
format.js
end
end
The client side ajax/javascript triggers this action and receives the json as response. It looks like this:
someCoffeescripAction = ->
$.ajax
type: "post"
dataType: "json"
data:
some_data_name: some_data_content
url: "some_url/some_controller_action"
success: (data, status, xhr) ->
do_something_with_the_response(data)
error: (xhr, textStatus, errorThrown) ->
Of course this don't work, as I am not allowed to render twice in the same action. But then what to do?
What does your javascript looks like? Do you fetch the controller action by ajax? If so, then you just have to wait until the ajax call is done, and then trigger a re-render of your partial, either by using the just fetched json data, or by calling another ajax function.