Rails 3.2.1 - Getting Javascript variables/data to Rails Controller - javascript

I'm working on a Rails 3.2.1 app and would like to pass some Javascript variables to the Rails controller. Here are some more details:
my js fiddle: http://jsfiddle.net/PauWy/475/
and what fiddle doesn't show, a jQuery UI sortable: $("#menu-items").sortable();
I would like to work with the following information in my Rails 'execute' method in the ThingsController for each item:
Whether or not the item is visible (I think I should do something like $('#item_1).is(':visible')
Which one of the following is displayed - "Add", "Reduce", or neither
the id of the item
the order/position of the item in the sortable list
My take would be to send an AJAX with the above data to the 'things/execute' action, and somehow route it and respond_to the incoming AJAX.
I know vaguely how some bits and pieces should look like, but I'm having a hard time putting everything together. Would really appreciate some help!

So, you need to parse you HTML to get information from it
Example
HTML :
<div id="my_content">
<div id="div1" class="reduce" style="visibility: visible;"></div>
<div id="div2" class="add" style="visibility: visible;"></div>
<div id="div3" class="add" style="visibility: visible;"></div>
<div id="div4" class="reduce" style="visibility: visible;"></div>
<div id="div5" class="reduce" style="visibility: hidden;"></div>
<div id="div6" class="add" style="visibility: hidden;"></div>
<div id="div7" class="add" style="visibility: hidden;"></div>
<div id="div8" class="reduce" style="visibility: hidden;"></div>
</div>
Then you can parse it to JSON (using jQuery) :
Javascript :
var parsed_data = {}
var order = 1
$('#my_content > div').each(function() {
// Some if else
var element_class = $(this).hasClass('reduce') ? 'reduce' :
( $(this).hasClass('add') ? 'add' : 'unkown')
parsed_data['data'+ order] = {
element_id: $(this).attr('id'),
display_class: element_class,
visibility: $(this).css('visibility'),
}
order++
})
Then you call your controller with AJAX :
$.ajax({
url: "<CONTROLLER_URL>",
type: "POST",
dataType: 'json', // data returned, not data sent
data: parsed_data
}).done(function(data) {
console.log('Done')
})
Ruby Controller :
def your_controller_function
params.each do |key, div|
print "DIV N°#{key}"
print " Id #{element_id}"
print " Displayed class #{display_class}"
print " Visibility #{visibility}"
end
end
I hope it's not too messy and it helped.

Related

How to retrieve shopping cart items, implementing LocalStorage

How do I retrieve information stored in a js file? I assume I am labelling my node elements in HTML incorrectly
I'm hoping to gain a better understanding of how to retrieve a function node from localStorage
Below are the key factors I am trying to get using getElementById into local storage from post HTML.
This is not everything in my listing.html document, I have excluded everything but what I think are essential elements
<div class="listing">
<div class="container-form">
<div class="mySlides fade">
<div class="numbertext">1 / 3</div>
<img class="img" value(src)="1" id="img" src="images/4.JPG" alt="img1">
</div>
<div class="infoBox">
<h5 post="weight" id="weight" value="7.00">7.00 : Under - 16 oz</h5>
</div>
<div class="column-bottom">
<div class="add-button">
<div class="add-button" method="post">
<p><input type="submit" onclick="addListing()" class="btn"></input></p>
<div class="buy-button">
<span class="price" post="price" id="price" value="60">$60</span>
<button type="button" class="btn" onclick="window.location.href='cart.html'" onclick="addListing()"
;>BuyMe</button>
</div>
</div>
</div>
</div>
</div>
</div>
I am trying to use the function below to store each element from the post HTML
function addlisting() {
let listing = ['listings'];
if (localStorage.getItem('listings')) {
listing = JSON.stringify(localStorage.getItem('listings'));
alert("added!");
}
listing.push({ 'listingId': listingId + 1, image: '<imageLink>' });
listingsId = listingsId + 1;
var listingsName = document.getElementById('name').innerHTML;
var listingsPrice = document.getElementById('price').getAttribute('data- value');
var listingsImage = document.getElementById("img").src;
var listingsWeight = document.getElementById('weight').getAttribute('data- value');
value = parseFloat(listingsPrice, listingsWeight).toFixed(2);
localStorage.getItem('name', 'price', 'img', 'weight', JSON.stringify(listingsName, listingPrice, listingsImage, listingsWeight));
}
here is the $(document).ready(function(){ function I'm hoping to implement into my code, I got this from another Stack Overflow page as it was the most fitting however I am yet to understand each component.
$(document).ready(function () {
$('#Btn').load(function () {
let listings = [];
if (localStorage.getItem('listings')) {
listings = JSON.parse(localStorage.setItem('listings'));
}
listings.push({ 'listingId': 1, image: '<imageLink>' });
});
});
my question again is how do I then execute this function using onload Onto a separate HTML, called cart.html. I did not display my cart.html file because there is nothing pertaining to this question on it. And furthermore how to go about styling Onload events that retrieve information from localStorage.
P.S.
There is an alert function within my first .js excerpt addListing(), that does not fire when clicked. probably a sign of bad programming. I've just never found a straightforward answer

Working JQuery Script not working after ajax post response

I'd really appreciate any help!
I have a working jquery script. When a div is clicked, it updates the css class to active and executes a working ajax response.
I also have a filter functionality that works too. When a checkbox is ticked it calls a new list of div's from mysql with all the same class properties. However, when any of these new div's are clicked the ajax response doesn't work. If anyone could help I would be incredibly grateful!
HTML:
<div id="result" class="results">
<div class="w-embed"><img src="images/loader.gif" id="loader" width="" "200px"="" style="display:none;">
<?php
$sql="SELECT * FROM `posts`";
$result=$con->query($sql);
while($row=$result->fetch_assoc()){
?>
<div class="c-card" data-id="<?=$row['id'];?>">
<h1 class="s-h2">
<?=$row['title'];?>
</h1>
<!-- <div class="s-para m-light m-small"><?=$row['description'];?></div> -->
<div class="c-stats">
<div class="s-stat">Pay:
<?=$row['pay'];?>
</div>
<div class="s-stat">Deadline:
<?=$row['deadline'];?>
</div>
<div class="s-stat">Location:
<?=$row['location'];?>
</div>
<div class="s-stat">Cat:
<?=$row['category'];?>
</div>
</div>
<p class="s-para">
<?=$row['description'];?>
</p>
Find Out More
</div>
<?php }?>
</div>
</div>
Javascript:
<script>
$('.c-card').on('click', function(event){
event.preventDefault();
$('.c-card').removeClass('active'); //Removes class to all
$(this).toggleClass('active'); //Applies class
var action = 'data';
var dataId = $(this).data("id");
$.ajax({
type:"POST",
url:"ajax/selected.php",
data:{action:action,id:dataId},
success: function(response){
$("#jobber").html(response);
$("#changeme").text("altered");
}
});
});
</script>
This is the outputted response from the filters:
'<div class="c-card" data-id="'.$row['id'].'">
<h1 class="s-h2">'.$row['title'].'</h1>
<div class="c-stats">
<div class="s-stat">Pay:'.$row['pay'].'</div>
<div class="s-stat">Deadline:'.$row['deadline'].'</div>
<div class="s-stat">Location: '.$row['location'].';</div>
<div class="s-stat">Cat: '.$row['category'].'</div>
</div>
<p class="s-para">'.$row['description'].'</p>
Find Out More
</div>';
So my question is how do i make the new divs (called from the filter) to continue to be triggered and change class + execute the ajax query.
Thanks so much in advance!
I have been thought your actual problem was the ajax response is getting null.
<div class="c-card" data-id="<?=$row['id'];?>">
You are using the data-id attribute in the HTML section. But the script handles the id attribute using for getting the id. So the id is getting null for ajax call, Please use the below code or change the data-id attribute to id in the HTML section as you like.
var action = 'data';
var dataId = $(this).data("data-id");
"id" and "data-id" are different attributes for HTML. Please use same attributes in HTML and script
maybe because there is no html(div|| p || span ||...) element that have id of id="jobber"

Why does my view function render data but it won't show up in the browser? (AJAX/Django)

I have finally achieved that my Javascript on 'click' function and AJAX work handy in collaboration with my view function that calls data from an API. But now I have one more issue:
The data from the API is forwarded smoothly to the html containers that contain the according variables. But in my browser I don't see the content being displayed?!
Why is that?
I don't have a success function set up in AJAX so far, since I understood that the view function renders the frontend so there is no need for AJAX success function in that case?
In advance thank you so much for your inputs.
View
import requests
from django.shortcuts import render
import json
def team_update(request):
team_id = request.GET.get('team')
response = requests.get(f'http://www.api-football.com/demo/api/v2/teams/team/{team_id}')
team_data = response.json()
teams = team_data.get('api', {}).get('teams', [])
if teams and len(teams) == 1:
teams = teams[0]
return render(request, 'index.html', {
'name': teams['name'],
'country': teams['country'],
'founded': teams['founded'],
'logo': teams['logo'],
'venue_capacity': teams['venue_capacity'],
})
Javascript/Ajax:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id},
success: function(response) {
console.log(response)
}
});
});
HTML (the key part):
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="{% static "images/club_flags/Clubs/Germany/FC Bayern München.png" %}" alt="Manchester United">
</div>
<div class="selectedClub">{{ name }}</div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded">{{ founded }}</p>
</div>
Debug:
You need to utilise the response data from within your success function, rather than simply logging it. I'll make some assumptions about your page, say for example you currently have the following
<body>
<!-- all your other stuff on the page -->
<div id="container-element">
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="" alt="">
</div>
<div class="selectedClub"></div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded"></p>
</div>
</div>
</body>
If that was how your page is currently set up, then in your success function of your AJAX call, you could do this:
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id },
success: function(response) {
$('container-element').html(response);
}
});
Which will replace the content inside your actual page.

Passing CSS Values Through JavaScript to Partial View

I am working with an MVC Entity Framework Webapp. I have a view that displays other partial views that are updated every 30 seconds. The issue is the dynamic progress bar I am using does not fill up at all and I have tried everything I know. The problem I think is the css that gets passed to the partial view ("width", current_progress + "%"). Here is a pic and the bar is supposed to be over half full...
Controller methods:
public ActionResult Dashboard()
{
ViewBag.SumofDon = db.tblDonors.Sum(s => s.DonationAmount);
return View(db.tblDonors.ToList());
}
public ActionResult Progress()
{
return PartialView("_Progress", db.tblDonors.ToList());
}
Dashboard.cshtml:
#model IEnumerable<bssp.Models.tblDonor>
#{
ViewBag.Title = "Dashboard";
}
#section Scripts{
<script>
function loadProgressPV() {
$.ajax({
url: "#Url.Action("Progress")",
type: 'GET', // <-- make a async request by GET
dataType: 'html', // <-- to expect an html response
success: function(result) {
$('#progress').html(result);
}
});
}
$(function() {
loadProgressPV(); // first time
// re-call the functions each 10 seconds
window.setInterval("loadProgressPV()", 10000);
});
</script>
<script>
$(function () {
var SumofDon = #ViewBag.SumofDon;
var current_progress = (SumofDon / 20000) * 100; // 20000 is the goal that can be changed
$("#dynamic")
.css("width", current_progress + "%") //This causes the problem?
});
</script>
}
<div class="container-fluid">
<div class="row" id="progress">
#Html.Partial("_Progress")
</div>
</div>
Partial view:
#model IEnumerable<bssp.Models.tblDonor>
<div class="row">
<br /><br /><br />
<div class="col-md-12">
<div class="well bs-component">
<h4>#String.Format("{0:C}", #ViewBag.SumofDon) out of $20,000<br /></h4>
<div class="progress progress-striped active">
<div class="progress-bar" id="dynamic" style="width: 0%"></div> #*The width is what gets updated because it found the id of dynamic*#
</div>
</div>
</div>
</div>
Any help would be awesome and thanks in advance!
I think your issue is that you pull in the html from the partial with a style="width: 0%" but then jQuery that adjusts the css, $("#dynamic").css("width", current_progress + "%"), is only run on page load, not after the partial reloads. You have two options to fix this,
Run the jQuery function after the razor loads in from the partial, in the success method of the ajax.
Since you are using razor to create the partial, why not just do the calculation right there? That way the partial comes in already set up with the width set. This is the easier and faster option of the two.

Change the content of 3 divs using javascript and ajax

i'm using rails 4 and javascript and here's my question:
i need to change the values of 3 divs using a button. The values of the divs are generated by a ruby function that came from the controller of that page.
Code:
<% $number= randNumbers %>
<div id="1"><%= $number[0] %></div>
<div id="2"><%= $number[1] %></div>
<div id="3"><%= $number[2] %></div>
<button id="btn1" >Click me!</button>
Here's the ruby method
def randNumbers
n1=rand(1..10)
n2=rand(1..10)
n3=rand(1..10)
return array=[n1,n2,n3]
end
So i need to recall the ruby function to generate new random numbers everytime i click on the button "btn1" without reloading the page.
I know that i have to use ajax or jquery, but i do not really know how to use it with ruby methods.
Thanks for helping :D
You can try the following:
HTML code in View:
Remove the code <% $number= randNumbers %>
Change the code to:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<button id="btn1" >Click me!</button>
Javascript Code in View:
$( document ).ready(function() {
call_ajax();
});
$("#btn1").click(function(){
call_ajax();
});
function call_ajax(){
$.ajax({ type:'POST', url:'/controller/get_random', data: {},
success:function(data)
{
$("#1").text(data.arr[0])
$("#2").text(data.arr[1])
$("#3").text(data.arr[2])
},
error:function()
{
// Handle error if Ajax fails
}
});
}
Method in Controller:
def get_random
n1=rand(1..10)
n2=rand(1..10)
n3=rand(1..10)
array=[n1,n2,n3]
render json: {arr: array}
end
Also add routes in routes.rb: post '/controller/get_random'

Categories