Rails: passing value: view to controller to view with Javascript/Ajax - javascript

In one of my forms, I have an element called event_id which value I select from a dropdown box. Once I select event_id, I want to use Ajax to call the controller, and return panel_event_id as a ruby variable that I can use in the rest of the form. Here's what I'm doing:
In routes.rb, I have the following:
match 'panel_event_id', :to => "panels#event_id"
I have the following javascript function (not sure about the syntax):
<script type="text/javascript">
$('select').change(set_session_event_id);
function set_session_event_id()
{
var event_id = document.getElementById("event_id");
var event_id_value = event_id.value;
$.post('panel_event_id', { set_event_id: event_id_value });
}
</script>
What do I put in my panel_controler.rb, in the following method:
def panel_event_id
end
and how do I act on it back in my view?

You could render a json in your controller :
def panel_event_id
...
render :json => panel_event.as_json(:only => [ :id ])
end
After that, you could handle the success event of the post method. See the doc here : http://guides.rubyonrails.org/layouts_and_rendering.html and here http://api.jquery.com/jQuery.post/ and here http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html#method-i-as_json.

Related

Laravel- How to "catch" a variable with Javascript passed to a blade.php view

so i'm currently working on a project and i want to add a calendar to one view, i'm using FullCalendar, the calendar is shown in the view but i'm currently trying to add events to that calendar, those events are going to be "pulled" from my database into the calendar to be displayed, now the problem is that when i pass the array with the events to the blade.php view that contains the calendar a error comes up saying that the variable "events" is undefined and i don't know if i'm doing something wrong, here's the code:
RegisteredUserController.php
$events = array();
$citas = Cita::all();
foreach($citas as $cita){
$events[] = [
'title' => $cita->paciente_id,
'start' => $cita->hora_de_inicio,
'end' => $cita->hora_de_finalizacion
];
}
return redirect(RouteServiceProvider::HOME)->with(['events' => $events]);
RouteServiceProvider.php
public const HOME = '/home';
homeView.blade.php (This is where i get the error, in the line where i assign it to citas)
<div id="calendar">
</div>
<script>
$(document).ready(function(){
var citas = #json($events);
$('#calendar').fullCalendar({
header: {
left: 'month, agendaWeek, agendaDay',
},
events: citas
})
});
</script>
routes / web.php
Route::get('/home', function (){
return view('homeView');
})->name('homeView');
Not sure if it's helpful but i'm using Laravel's Breeze to handle the authentication of users, so when an user is aunthenticated they're redirected to the page where the calendar is.
i've tried the following
RegisteredUserController.php
return redirect(RouteServiceProvider::HOME, compact('events));
This one makes the whole calendar disappear:
homeView.blade.php
var citas = {{ Session::get('events') }};
Thank you in advance.
the return should be like this
return view('path_of_the_blade', compact('events'));
So then in View, you can use
<script>
var citas = #json($events);
</script>
On you controller, why don't you just simply use:
return view('homeView')->with(['events' => $events]);
or simplier:
return view('homeView', compact('events'));
This would surely pass the variable events on the blade file.
Then on your blade file, you will just reference it as:
var citas = {{ $events }};

How can I reorder the column sequence of my DataTable in my Django App?

I am doing a ajax request to pass some data from Views.py to the HTML file and render it using DataTables() javascript library.
The problem I am facing is that the displayed datatable is not following the column order that I would like to.
I don´t know if the solution is to reorder the json data that the datatable receives or to use some functionallity of DataTables().
What should be the best solution to reorder the table´s column? And how can I apply it to the code bellow?
Views.py
...
def test_table(request):
data_pers = {
'Product':request.GET.get('Product'),
'Length':request.GET.get('Length'),
'Cod':request.GET.get('cod'),
'partnumbetr':'42367325'
}
return JsonResponse({'data_prod':data_prod})
...
HTML
...
$.get('{% url "test_table" %}',
{Product:Product,Length:Length,Cod:Cod},
function (data_prod) {
var data_json_prod=data_prod['data_prod'];
var data_array_prod = [];
var arr_prod = $.map(data_json_prod, function(el) { return el });
data_array_prod.push(arr_prod);
$('#id_prod').DataTable({
destroy: true,
data:data_array_prod,
});
...

Re-render a page using jquery

In react, I could easily re-render a view by passing results from controller. I wish not to use React at this stage and was wondering if it's possible with JQuery?
I have few objects on page, and when clicked, I should see its content. Click the other object, I see its content etc. Sense? I was inspired by this dribbble.
I may not be doing this the right way but this is what I have:
Controller:
def index
selected_contract = params[:selected_contract] || current_user.contracts.last.id
#contracts = current_user.contracts.order(created_at: :desc).all
#selected_contract = current_user.contracts.find_by(id: selected_contract)
end
View:
<% #contracts.each do |contract| %>
<button class="ui button test" id="<%=contract.id%>"><%=contract.name%></button>
<% end %>
......................................
When clicked, show its content
....................................
<%= #selected_contract.name %>
JS:
$( ".ui.button.test" ).click(function(e) {
let { id } = this
console.log(id)
$.ajax({
url: `/url/${id}`,
type: 'POST',
success: function(result) {
//$('#listview').redraw()
console.log('success')
}
});
});
Routes are set properly so I get the params in the controller just fine. Is there a re-render a view, just like rerender a prop in React for jquery? Am I doing this the correct way?
If you are using jquery listview this should work.
$( "#listview" ).listview( "refresh" );
Reference
https://api.jquerymobile.com/listview/#method-refresh
or since its rails you can reload or render the partial view in your server side as well.

Using jQuery to update multiple objects

I have a profile page where I render all of the user's lists using a partial:
users/show.html.erb
<%= render #lists %>
For each list I show how many wishes are associated:
lists/_list.html.erb
<p class="muted" id="wishes_count"><%= pluralize(list.wishes.count, "wish") %></p>
I'm using drag and drop to allow the user to move wishes from one list to another using jQuery sortable.
Right now, I'm using the following code:
wishes.js.erb
$(document).ready(function(){
$('.user_list_wishes').sortable({
connectWith: ".user_list_wishes",
items: ".user_list_wish",
placeholder: "sortable_placeholder",
update: function(e, ui)
{
if (this === ui.item.parent()[0])
{
item_id = ui.item.data('item-id');
list_id = $(this).data('list-id');
position = ui.item.index();
$.ajax({
type: 'POST',
url: $(this).data('update-url'),
dataType: 'json',
data: { id: item_id, wish: { row_order_position: position, list_id: list_id } }
}),
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
}
}
})
})
This line of code:
$("#wishes_count").html('<%= pluralize(list.wishes.count, "wish") %>')
makes my application throw a NoMethodError undefined method 'wishes' for nil:NilClass
I believe it has something to do with how I render lists and reference them individually in my javascript?
Any suggestions on how to solve this problem is much appreciated!
You must handle the scenario where list is null using the following condition:
$("#wishes_count").html('<%= pluralize(list ? list.wishes.count : 0, "wish") %>')
I think the problem could be in your render call - according to the documentation:
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<%= render #customer %>
Assuming that the #customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the #customer instance variable in the parent view.
So check that this is the case - do you have a partial called _lists.html.erb and a parent variable called list?

JQuery-Ui Autocomplete not displaying results

I am trying to display autocomplete results for a list of managers. I have the following code:
Application.js
function log(message) {
$( "<div/>" ).text( message ).prependTo("#log");
}
$("#managers").autocomplete({
source : function(request, response) {
$.ajax({
url : "/managerlist",
dataType : "json",
data : {
style : "full",
maxRows : 12,
term : request.term
},
success : function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value : item,
label : item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
Project controller
def manager_list
list=Project.all.map{|i|i.manager_user_id}
arr= [].concat(list.sort{|a,b| a[0]<=>b[0]}).to_json
render :json =>arr
end
Routes.rb
match '/managerlist' => 'projects#manager_user_id'
_form.html.erb
<p>
<%= f.label :manager_user_id %><br />
<input id="managers" />
</p>
The following code is fine, I don't recieve no errors in firebug. However when I try to enter a managers name for example James Johnson the name won't appear. I have also tried putting the whole function in the _form.html.erb and wrapped it in tags this didn't work. Is there any idea why this is happening
So I've managed to fix my error, which was because of the ordering of Jquery core and Jquery ui.
I've got the managers to be listed. In the image below.
From the image it can be seen that when I type 'Arm' it brings the entire list of managers, when it should display 'Deshawn Armstrong'. I understand that this is most probably to do with my project controller below
Project controller
def manager_list
list=Project.all.map{|i|i.manager_user_id}
arr= [].concat(list.sort{|a,b| a[0]<=>b[0]}).to_json
render :json =>arr
end
Check the response in the Firebug console and make sure the string is in proper json format for the autocomplete.
It appears that you are just returning an array. The dataType setting in .ajax doesn't convert to json; it's just expecting that format back. If you are not sending json back from your url : "/managerlist", this may be the problem.
Actually, provided your ajax function is working correctly, you could just:
return response(JSON.stringify({ results: results }));
jsfiddle example of JSON.stringify: http://jsfiddle.net/xKaqL/
Based on your new information, you need to add a minLength option to your autocomplete.
$("#managers").autocomplete({
minLength: 2, // 2 or whatever you want
// rest of your code

Categories

Resources