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.
Related
I'm trying to insert modal window html code dynamically upon user click on which item otherwise i load all of the items' modal window code in the html. I also have some inputs in the modal window loading from Flask/Sql and i want to let user update any of them so i need to send data back to python on submit button clicked. But right now because of i have too many modal windows (even though they have separate ids) i couldn't find a way to achieve this
Here is my code:
routes.py
#app.route('/viewApart', methods=['GET', 'POST'])
def viewApart():
apts = []
getApts = db.engine.execute("SELECT * FROM apartments")
for a in getApts:
apts.append((a))
rooms = []
getRooms = db.engine.execute("SELECT * FROM rooms")
for r in getRooms:
rooms.append((r))
return render_template('apartments.html', title=_('Apartments'), apts=apts, rooms=rooms)
apartments.html
....
<section class="container">
<div class="row">
.. below some gallery code to show individual items from apts ..
{% for apt in apts %}
<div class="col-md-3">
<a href="javascript:void(0);" class="widget__v2 apt-widget rounded-corners box-shadow__v1 white" data-anchor="modalwindow" data-target="edit-apartment{{ apt[0] }}" id="apt{{ apt[0] }}">
<div class="widget-header">
<figure class="image h-180">
<img src="{{url_for('static', filename='_assets/img/apt/{{ apt[0] }}.jpg')}}" alt="" class="image__scaledown">
</figure>
.. below model window ..
<div id="edit-apartment{{ apt[0] }}" class="modal large">
<div class="modal-wrapper">
<div class="modal-inner">
<div class="modal-header">
<h3 class="title">{{ _('Edit Apartment') }}</h3>
</div>
<div class="modal-content">
<div class="row medium-gutter">
<div class="col-md-6">
<div class="row medium-gutter">
<div class="col-md-8">
<div class="form-group">
<div class="form-group-title clearfix">
<label for="apt_display_name">{{ _('Display Name') }}</label>
<div class="lh-24 text__default-grey pull-right" data-tooltip="true" data-tooltip-direction="up" data-multiline="true"
data-content="..">
<i class="icofont-question-circle"></i>
</div>
</div>
<input id="apt_display_name" type="text" class="form-control" value="{{ apt[1] }}">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label for="apt_number">{{ _('Apt. Number') }}</label>
<input id="apt_number" type="text" class="form-control" value="{{ apt[2] }}">
</div>
</div>
</div>
.. and so on...
.. and submit button ..
{{ _('Save Changes') }}
</div>
</section>
Right now even with multiple model windows, i can display the current data in modal window, so what i want to achieve this upon clicking on btnSubmit button i need to send all input values back to python so i can update my sql or insert new one. Please let me know if more code is needed..
Thanks
If I am understanding your question correctly - a skeleton version of your page would be something like this
<!DOCTYPE html>
<html>
<body>
<p>INTRODUCING MY AWESOME SITE AND 2 DIVS YOU CAN CLICK</p>
<div id="apt_1_modal">
<input id="apt_1_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
<div id="apt_2_modal">
<input id="apt_2_text"></input>
<a onclick="myFunction(event)">Submit</a>
</div>
</body>
</html>
You will need JavaScript to handle the user interaction - the script would look something like this. You can either append this script directly to your render_template output or you can append it as a file.
The script will do 2 things - first capture what your user is inputting and second, send that data over to flask
<script>
function myFunction(e) {
//FIRST WE CAPTURE THE VALUE THAT THE USER INPUTS
let userInput = {toSend: e.currentTarget.previousElementSibling.value}
//THEN WE SEND IT TO THE FLASK BACKEND USING AJAX (Fetch API)
fetch("/api/path/to/flask/route", {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userInput)
}
</script>
Now you need a function that can handle the userInput data
Backend
from flask import Flask, request #import main Flask class and request object
#app.route('/api/path/to/flask/route', methods=['POST'])
def capture_userinput():
req_data = request.get_json()
recd_data = req_data['toSend']
your_code_to_push_data_to_db(recd_data) #Depends on your ORM/DB
I hope I have given you an idea of how to go about - You will most certainly have to change the way to capture userInput, tweak the fetch call and send/capture additional data in your flask api.
I have got this part of code which represents an item in this bunch of items:
http://www.gosu.cz
<script> //this script is used to set A TAG href via it's ID
$(document).ready(function() {
$('img').click(function () {
var alt = $(this).attr("alt")
var strLink = "link&Key=" + alt;
document.getElementById("link").setAttribute("href",strLink);
});
});
<!-- Least Content -->
<main id="least">
<div class="container-fluid">
<div class="least-preview"></div> //div used to show selected item
<ul class="gallery start" id="gallery_w">
<!-- item -->
//definition of item, which carry additional informations in data-caption
//However having A TAG using ID to set HREF does't work when ID is not in ""
<li class="item col-xs-12 col-sm-6 col-md-4">
<a href="http://placehold.it/857x712" data-caption="<h3>Header</h3> <p>description </p> <a id=link>Zobrazit produkty</a>" />
<img src="http://placehold.it/857x712" class="img-responsive" alt="chair" />
</a>
</li>
<!-- /item -->
and if you click on first item (http://imgur.com/a/VdKQK) which I work on right now you can see displayed data-caption (which can be seen in this code). What I need is to make that A TAG working via id. It normaly works when it's used outside tag parameters but I can't run it inside parameter. Where is my syntax mistake please?
i am currently trying to create pagination feature. I am using bootstrap for css and jQuery.
There are total of 8 divs that contains a tags.
in my html file, i wrote
<div id="articleArea" class="row">
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
<div class="col-md-4 postTitle">
post title
</div>
</div>
what I want to do is replacing each href in a tags, based on the response from my ajax call. I will just post success part of .ajax since other parts are completely functional and irrelevant to my question. my ajax call is returned in json format and var result is an array that contains 8 different hrefs that need to be assigned to each a tags in postTitle divs.
success: function(data){
var result = data["result"];
for(i=0; i < result.length; i++{
postTitle = result[i];
$(".postTitle.a").html(postTitle);
}
},
If i execute this code, a href are shown briefly but it disappears within a second. How can I fix this? and if there is better way to implement this feature, please do comment! Would love to be hear any feedbacks.
You need to run iteration over a tags instead of running iteration over results
$(".postTitle a").each(function(i) {
postTitle = result[i];
$(this).attr("href",postTitle);
});
This would run over each href tag and replace the values accordingly
EDIT: it should be .postTitle a
Your selector would select all of the elements
$(".postTitle.a")
You should select each tag and set its href, in addition it is missing a space:
$(".postTitle a").each(function(index, value){
$(value).attr('href', result[index]);
});
$(document).ready(function() {
$('#pdf').change(function() {
var newurl = $('#pdf').val();
$('a.target').attr('href', newurl);
});
});
I am using the following bootstrap 3 html
<form action="#" role="form">
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 60px;">
<img id="logothumb" src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" /> </div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 60px;"> </div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new"> Select image </span>
<span class="fileinput-exists"> Change </span>
<input type="file" name="..." id="logo"
> </span>
Remove
</div>
</div>
</div>
<div class="margin-top-10">
Upload
Cancel
</div>
</form>
I have some javascript code to upload the file and also show an existing file from database when the code is first loaded.
var fileUploadControl = $("#logo")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
The problem is, the file upload control shows 'Select Image' even when there is
a file present i.e. shown from database in the img src. It should show the 'Change' - 'Remove' options. How do i get it to do that. It does this when a file is selected for the very first time however.
Thanks
If I understand you correctly, you will have an image present when your page is loaded. However, you only want "Change" and "Remove" visible, with "Select Image" hidden. To do this, you can simply hide your span containing "Select Image" when the page loads.
$('span.fileinput-new').hide();
Now you have your active page. If the default image is removed, I assume you want to then hide "Change" and "Remove" and then display "Select Image" again. In this case, you can set an event on your file input and toggle these based on if a file is currently uploaded or not.
$('#logo').on('change', function() {
// If a file is uploaded - hide "Select Image" and show "Change - Remove"
if($(this).val().length) {
$('span.fileinput-new').hide();
$('span.fileinput-exists, a.fileinput-exists').show();
// If a file is not uploaded - show "Select Image" and hide "Change - Remove"
} else {
$('span.fileinput-new').show();
$('span.fileinput-exists, a.fileinput-exists').hide();
}
});
EDIT - I played with this a while and have put together a JSFiddle that I think will help you out.
Check it out here
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