Hopefully this question isn't too similar to others out there. I've spent a number of hours researching it, but apparently I don't quite know the terms to search for.
Using Rails 4, I'd like to use an ajax request to load data from a database table and use it to update a chart. I have succeeded in doing this by making a controller method and view, populating the view with the data, and then fetching that via ajax. The question is: how can this be done without creating a view? My solution is not terribly elegant, and I'm hoping for some more excellent solutions. I need to make a few more charts, and I would rather not make new views for each one if possible.
user_controller.rb
def asset_allocations
#AAPL = ....
#GOOG = ....
end
asset_allocations.html.erb
<div id="AAPL">
<%= #AAPL %>
</div>
<div id="GOOG">
<%= #GOOG %>
</div>
assets.js.erb
$(document).ready(function() {
$.ajax({
type: 'GET',
url: "/allocations",
cache: false,
success: function(html) {
var AAPL = $(html).find('#AAPL').html();
var GOOG = $(html).find('#GOOG').html();
show_pie_chart(parseFloat(AAPL), parseFloat(GOOG));
}
});
});
use
head :no_content
in last line of action
where view not need
Related
In my project I have rows of modules loaded from Partial views.
So imagine a grid of small squares with information.
There is a popup dialog for all of them, that displays the data of the clicked module.
Currently when I submit a change in the dialog, the javascript reloads the entire page. BUT, this takes a long time, and I need to be able to refresh only the one dialog.
I can imagine to make a separate js function for each type of module, and then pass some data in, so jquery can find the specific module, and then make an ajax get, for the data. But this requires me to do all the data insertion from js always. instead of using razor and MVC's built in awesomeness.
Does anyone know of a way, to call a partial view inside a div?
Also in the future I will need to reload "some" but not all the modules in an interval refresh. So for future proofing purposes:
What im looking for is something like:
function reloadElement(row, column, id){
var target = $("#div1");
// todo find row and column
target.html.partial("url", model); //<----- looking for something like this. cross fingers.
}
Thanks to GregH for a few key words, that lead to some ideas.
I solved it myself, so if you land on this problem also, here is how i solved it:
Controller:
You want to make your controller return PartialView("somePartialViewUrl", new SomeModel()), apparently saving the model and relying on the data collection isn't good enough, i hadto make a new instance of the model.
Javascript
in the "click" that handles the event, put:
$.ajax({
url: "controllerName/actionName",
data: JSON.stringify({ row:1,column:2 .... }),
contentType: "application/json",
dataType: "html",
type: "POST",
success: function (partial) {
$("#div2").html(partial);
}
});
this will override the html in your "#div2".
im sure you can also use $("#div2").innerHTML = partial; or $("#div2").load("url",parameters); and probably many other ways.
done.
I'm working on a rails form where I need to send an array created in Jquery to my rails controller. I've had a hard time getting the data in the proper format.
I managed to get the Jquery array to send through AJAX when doing an update of this model. It sends the normal PATCH and an additional PATCH for the array parameter. So 2 updates. Everything works find for updates, it's a bit hacky but does what I need it to.
This doesn't work on create though since I can't send two POST requests to create the same object? Does that make sense?
So I guess my question is how can I get my AJAX data to tag along with the normal form submit?
Here's
$('#employer_job_submit_button').on('click',function(){
$.ajax({
url:"/jobs/<%= #job.id %>",
type:'PATCH',
dataType:'json',
data:{
job: {
benefits: tags_array
}
}
});
});
Here's my view (part of it)
<%= form_for #job, :html => {:class => 'profile_form'} do |f| %>
.....
<div>
<%= f.submit "Post Job", class: "btn btn-primary btn-block", id: "employer_job_submit_button" %></div>
</div>
<% end %>
I tried separate code just for creating new jobs. Like this:
$('#employer_job_submit_button').on('click',function(e){
e.preventDefault();
var form_data = $('form').serialize()
$.ajax({
url:"/jobs",
type:'POST',
dataType:'json',
data:{
job: form_data
}
});
});
That sends all my form data through AJAX but I can't figure out how to add the "benefits" array to the form data. Also this is not really what I want to do because it bypasses the standard Rails form.
I just want to add my Jquery created array along with the form data.
That sends all my form data through AJAX but I can't figure out how to add the "benefits" array to the form data.
You may simply add the stringified array version to your data.
From:
dataType:'json',
data:{
job: form_data
}
To:
data: {
job: form_data,
benefits: JSON.stringify(tags_array)
}
In this way you will receive on your server two variables like in the following example:
job:firstname=Mickey&lastname=Mouse
benefits:["Saab","Volvo","BMW"]
Instead, if you want to continue to add to your serialized form data your array you can use jquery param like in the following:
var form_data = $('form').serialize() + '&' + $.param({"benefits": tags_array});
In this last way you need to decode the job parameter in your server side in order to extract the **benefits" array.
I seem to be having some trouble finding some good information on how to go about dynamically presenting forms on the same view. What I mean is, for example, A user clicks an "Add Sub-element" link on the show view for an "Element", and then is presented with a small form for adding a Sub-Element, and of course the same type of thing for editing existing Sub-Elements, on the same Show View using AJAX/JS/jQuery or something.
I was trying REST-in-place, but to no avail, as I have several nested objects (some within other nested objects), and that doesn't seem to work well with in-line-editing.
I believe my lack of information is coming from using incorrect search terminology, so any help would be appreciated to point me in the right direction.
Thanks in advance.
There are a lot of different ways to do it, one is using remote forms, like this railscasts example or the detailed answer on this question. Another would be to call a controller from jQuery and render (similar to my code here):
in javascript:
$(document.body).on('click', '#user-list-body', function (e) {
var url = '/get_user_list/
$.ajax({
url: url,
datatype: 'html',
type: 'GET',
success: function(data){
$('#user_table tbody').append(data);
}
});
});
in controller (note: drastically simplified version):
def get_user_list
#users = User.all
respond_to do |format|
format.html { render :layout => false, :partial => 'users/users_list'}
end
end
I have been using django for almost 6 months now and it works fine for almost all kind of websites I do.
However , recently I stumbled upon an issue when I was doing a website, where a user gets notified about any blog post the other user updates.
My approach was this :
From my template I keep doing an ajax call like this :
$(document).ready(function() {
setInterval(function(){get_updates();}, 10000);
function get_updates(){
$.ajax({
type: "GET",
datatype: 'json',
url: "{% url 'models.views.update_notification' %}",
success: function(data) {
if(data.updated){
$.("content").load('notifications.html');
}
}
})
})
});
}
class UpdateNotificationView(View):
def get(self, request):
user = FriendUser.objects.get(name='friend')
msg = {"updated" : user.is_updated()}
return HttpResponse(simplejson.dumps(msg))
Assuming that notifications.html is just a partial included in every page:
<div id='divid'>{{ notification }}</div>
The problem here is that , I don't think its a good Idea to keep doing ajax calls like this every x seconds/minutes.
Is there a way to push updates from the backend as soon as a database is updated directly to the browser , without polling for updates like this ?
Or is django not made up for it ?
I guess you should have a look at django-comet or any othe comet-like project.
It will allow you to push a response from server to the user's browser.
Wiki page on Comet: http://en.wikipedia.org/wiki/Comet_(programming)
Also, let me share a link to a great answer on this topic: https://stackoverflow.com/a/4403209/2795926
I have a following code that is part of the _form.html.erb code. Basically I have a form in which I have a observe_field function where on change, it will set fields' values without refreshing the page. Following is my html code:
<script type="text/javascript">
// When DOM loads, init the page.
$(function() {
// Executes a callback detecting changes with a frequency of 1 second
$("#id_element_placeholder").observe_field(1, function( ) {
$.ajax({
type: "GET",
dataType: "json",
url: "/students/get/" + this.value,
success: function(data){
$('#last_name').attr('value', data.student.last_name);
$('#building').attr('value', data.student.building);
$('#room').attr('value', data.student.room);
}
});
});
});
</script>
Problem here is that I'm exposing lot of my code in javascript. Is there a better way to do it without exposing code in javascript?
Here is what my controller looks like:
def get
#student = Student.find(params[:id])
respond_to do |format|
format.html
format.json { render :json => #student }
end
end
Basically I get an id in a form and from there I have to get the corresponding object and update the fields on the page.
Assuming your design requires you to make AJAX calls to query student info by id, then you need to expose a URL for the call. If you don't want to expose a JSON data structure, you could return a chunk of HTML (instead of JSON), and replace the contents of the container of all of the controls you mention above.