I have this webpage i made,just to get started with web, based on this template.
http://ironsummitmedia.github.io/startbootstrap-freelancer/#
where on clicking the thumbnails in portfolio, another webpage opens with more details on the picture. The code i have written is making the page load. I want to implement it exactly as in this template.
html (for thumbnails) :
<div class = "pictures ">
<div class = "container ">
<div >
<center><b><text>PORTFOLIO</text></b></center>
</div>
<div class = "pics">
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src = "glass.png" src = "cabin.png" id="cabin" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "cake.png" id="cake" alt="" />
</div>
</div>
</div>
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src = "glass.png" src = "circus.png" id="circus" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "game.png" id="game" alt="" />
</div>
</div>
</div>
<div class = "column">
<div class = "col-md-4">
<div class = "thumbnail">
<img data-src="glass.png" src = "safe.png" id="safe" alt="" />
</div>
<div class = "thumbnail">
<img data-src="glass.png" src = "submarine.png" id="submarine" alt="" />
</div>
</div>
</div>
</div>
</div>
</div>
Jquery for opening new page :
$(".pictures .thumbnail img").click ( function () {
window.location.href = this.id +".html";
});
What changes should i make to my code which allows me to open pages without loading/refreshing?
thanks in advance!
You should learn some AJAX to achieve this. Read the jQuery Docs on AJAX for more info.
Ajax is a client-side script that communicates to and from a server/database without the need for a postback or a complete page refresh. The best definition I've read for Ajax is “the method of exchanging data with a server, and updating parts of a web page - without reloading the entire page.” Source: Seguetech
Here is some example AJAX and jQuery:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).serialize();
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#result").html(returnhtml);
$("#loadingimg").hide();
}
});
});
});
DEMO
Be dauntless. It looks sort of confusing, especially just starting with jQuery, but trust me it isn't. You'll be glad you learned it.
The template you are referring to uses bootstrap modals. Also to get data on the fly to fill the modal you need to know Ajax. Boy Wonder already gave a definition. But you can also populate the modal without getting data from the server site, it can be static after all. You can learn about bootstrap modals from here http://getbootstrap.com/javascript/#modals
Related
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
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"
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.
In my app, i have a web page with lots of images whose source url is generated dynamically by making get request to the rails server, initially a default image is assigned to the source. After loading the page i make request to the server that return a json with new image URl, and then need to update the src of that image. Following is the code i am using in html.erb
<div class="inner">
<div class="span9 blog-head alert alert-info"><h3><%=#feeds.title%></h3></div>
<%#feeds.entries.each do|feed|%>
<div class="thumbnail feeds span6">
<div class="row title lead">
<span class="span6"><%=link_to feed.title,feed.url,target: "_blank"%></span>
</div>
<div class="row content">
<input type="hidden" class="image-feed-url" value="<%=feed.entry_id%>">
<!-- need to update src of following img tag -->
<img class="span2 desc-img thumbnail" src="/assets/default.jpg" alt="RSS">
<span class="span3"><%=feed.summary%></span>
</div>
<div class="row footer">
<%if feed.published%>
<span class="span3">Published on: <small><%=feed.published.to_date.strftime("%b, %-d, %Y")%></span></small>
<%end%>
<span class="span2 source">Source: <small><%=link_to 'Click here',#feeds.url, target: "_blank"%></span></small>
</div>
</div>
<%end%>
</div>
Need to update src in "img" tag having class "desc-img". In my JS file
$(document).ready(function(){
all_feeds = $('.inner .feeds')
for(i=0;i<all_feeds.length;i++)
{
element = all_feeds[i]
feed_url = $(element).find('.image-feed-url').val()
$.getJSON("/get_image_url?feed_url="+feed_url,function(data){
// data['link] is the actual image link returned by server
$(element).find('.desc-img').attr('src',data['link']);
});
}
});
I had also tried using div with background image instead of img tag and updating background image of div in JS but nothing works. I am new to Jquery and Ajax, any help will be appreciated.
try this :
$.getJSON("/get_image_url?feed_url="+feed_url,function(data){
$(element).find('.desc-img').removeAttr('src');
$(element).find('.desc-img').attr('src', '../' + data['link'] + '?' + Math.random());
});
Hope this helps.
I have 3 link in my HTML. When I click one of these a variable in the session must change.
How can I do that?
<div id="eng">
<a href="#" onClick="setLanguage('en')";>
<img id="eng_img" src="bandiera01.png" />
</a>
</div>
<div id="rus">
<a href="#" onclick="setLanguage('ru');">
<img id="rus_img" src="bandiera02.png" />
</a>
</div>
<div id="ted">
<a href="#" onclick="setLanguage('de');">
<img id="ted_img" src="bandiera03.png" />
</a>
</div>
setLanguage(txt) is a JavaScript function but I want to use it in ASP to save it in session.
You need send the information to server, you can post by a normal link or send by ajax. I think with in this case, is better you send by normal link, for example:
<div id="eng">
<a href="ChangeLanguage.asp?language=en">
<img id="eng_img" src="bandiera01.png" /></a>
</a>
</div>
<div id="rus">
<a href="ChangeLanguage.asp?language=ru">
<img id="rus_img" src="bandiera02.png" />
</a>
</div>
<div id="ted">
<a href="ChangeLanguage.asp?language=de">
<img id="ted_img" src="bandiera03.png" />
</a>
</div>
In the page of destination, you get the "language" information of the link.
You can address this issue in a couple of way:
Turn your links into submit buttons, put them inside a form, submit the page server side to manage the language change business logic. This is a classic asp approach. You have to rebuild the page server side.
Let the setLanguage() fire an ajax call to an asp page that retrieves the localized resources. On success, the resources are mapped into the corresponding elements of the DOM: maybe set this logic into a different function:
HTML
<div class="lang">
en
</div>
<div class="lang">
ru
</div>
<div class="lang">
de
</div>
SCRIPT
(function($){
window.setLanguage = function(langCode){
$.ajax({
type: "GET",
url: "myLanguageHandler.asp",
data: { "languageCode": languageCode },
async: true,
error: function (req, status, message) {
//manage the error
},
success: function (data) {
mapPage(data);
}
});
/*
* for demo purpose only
* console.log('Set language: ' + langCode);
*/
};
$('.lang a').bind('click', function(e){
window.setLanguage($(e.target).attr('data-lang'));
return false;
});
})(jQuery)