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.
Related
I have a row of links, and depending on which one is clicked, a certain file gets loaded inside the "main" #DIV_main area where things are seen/clicked/viewed.
The HTML file, say HOME.HTML is:
HOME.HTML
<DIV id="DIV_TOP_LINKS">
<a class="nav_links" id="a_a" href="File_one.php">one</a>
<a class="nav_links" id="a_b" href="MAIN_UI.php">MAIN</a>
<a class="nav_links" id="a_c" href="File_two.php">two</a>
</DIV>
<DIV id="DIV_main ">
<!-- files MAIN_UI.php, File_one/two.php etc go here -->
</DIV>
the Javascript is:
$(document).ready(function(){
$("#DIV_TOP_LINKS a").click(function(e){
e.preventDefault();
$("#DIV_main").load(e.target.href);
});
$("#BTN_a").click(function(e){ //these dont work
alert("helo a");
});
$("#BTN_c").click(function(e){ //these dont work
alert("helo b");
});
});
function CH_ANGE(th, txt)
{ switch(txt)
{ case "a_click":
$("#DIV_A_inputs").show();
$("#DIV_B_inputs").hide();
$("#DIV_C_inputs").hide();
break;
case "b_click":
$("#DIV_A_inputs").hide();
$("#DIV_B_inputs").show();
$("#DIV_C_inputs").hide();
break;
case "c_click":
$("#DIV_A_inputs").hide();
$("#DIV_B_inputs").hide();
$("#DIV_C_inputs").show();
break;
}
MAIN_UI.php file is as follows:
<div id="DIV_post_type">
<div id="BTN_a" onclick="CH_ANGE(this, 'a_click')">Button A</div>
<div id="BTN_b" onclick="CH_ANGE(this, 'b_click')">Button B</div>
<div id="BTN_c" onclick="CH_ANGE(this, 'c_click')">Button C</div>
<button id="BTN_Post_Wall" onClick="POST_AJAX_INP_to_PHP_BUTTON()">POST</button>
</div>
<div id="DIV_abc">
<div id="DIV_A_inputs">Div_A and other content
<input TYPE="TEXT" ID="inp_A" NAME="INP_A">
</div>
<div id="DIV_B_inputs">Div_B and other content
<input TYPE="TEXT" ID="inp_B_1" NAME="INP_B_1">
<input TYPE="TEXT" ID="inp_B_2" NAME="INP_B_2">
<input TYPE="TEXT" ID="inp_B_3" NAME="INP_B_3">
</div>
<div id="DIV_C_inputs">
<input TYPE="TEXT" ID="inp_C_1" NAME="INP_C_1">
<input TYPE="TEXT" ID="inp_C_2" NAME="INP_C_2">
</div>
</div>
So the issues which I do not know how to implement are:
If you see the $(document).load function, there are 2 more event handlers for $("#BTN_a").click and $("#BTN_c").click. These two did not work, and then I thought its because essentially, they are 'linked' when the document HOME.HTML loads. The items BTN_a and BTN_c will only be there on the main page if the "MAIN" link click triggers a load of file MAIN_UI.php inside the #DIV_main. Is there a way to link $(document).load functions to elements which will arrive later on the page? or another $(something).load function in jquery I can use?
Thanks a ton in advance.
I'm making a live search function using ajax on laravel 7 and it works just fine for the most part. However, i have a button that disables the functions of the search output. When the page first loaded the functions are successfully disabled. But when i run the live search, the output's function is enabled again. I'm guessing its because the live search output is taken from a partial view/html which then loaded to the main view/html. The function run without any problem just after the page loads because the DOM already loaded it. When i append a new view/html, the DOM doesn't recognize it.
Here is the ajax code
function fetch_data(page, query){
$.ajax({
url:"/search?query="+query+"&page="+page,
success:function(data){
$('#product-container').html('');
$('#product-container').html(data);
}
});
}
$('#search').keyup(delay(function(){
var query = $('#search').val();
var page = $('#hidden_page').val();
fetch_data(page, query);
}, 400));
This is the partial view
<div class="row">
#if(count($products) < 1)
<div class="col-md-12 text-center">
<h5>No results</h5>
</div>
#endif
#foreach($products as $product)
<div class="col-md-3" id="item">
<div class="product__item p-2" style="background: #dce0e2;">
<div class="thumbnail">
<img src="{{ asset('img/products/'. $product->image) }}">
</div>
<div class="product__item__text">
<h6 style=" white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{ $product->name }}</h6>
<h5>{{ rupiah($product->price) }}</h5>
</div>
<a href="{{ route('kasir.add.item', ['product_id' => $product->id]) }}" class="add-btn" id="{{ $product->id }}">
<div class="btn-success text-center m-2 p-1">
Add +
</div>
</a>
</div>
</div>
#endforeach
</div>
{{ $products->links('partials.pagination') }}
This is the controller
public function search(Request $request){
if ($request->ajax()) {
$query = $request->get('query');
$query = str_replace(" ", "%", $query);
$products = Product::orderBy('name', 'ASC')->where('name', 'LIKE', '%'.$query."%")->paginate(8);
return view('kasir.product_data', compact('products'))->render();
}
}
My question is can the DOM load the partial view as if it loaded at the same time as the page so that the jquery functions can work on the new view/html?
This should be your partial (only works if you add it through ajax requests). It will add the listeners you want, even after the DOM is completely loaded the first time. Rerunning the same piece of jQuery will re-establish the listeners you are expecting.
<div class="row">
....
</div>
{{ $products->links('partials.pagination') }}
<script>
$('#search').keyup(delay(function(){
var query = $('#search').val();
var page = $('#hidden_page').val();
fetch_data(page, query);
}, 400));
</script>
this is image that i want to doactually i have a div content,i have apply onclick event on that div when user click on that div the text between these tags should be sent to server and then display in the table as well.i have done something guid me where is the error actually,because $.ajax not working it raising an error
e.g: $.ajax is not fnction
players.html
<div class="selectize-control single">
<div class="selectize-input items has-options not-full">
<input type="text" autocomplete="off" tabindex=""
id="select_player" style="width: 146.75px; opacity: 1; position:
relative; left: 0px;" placeholder="Adauga jucator la echipa">
</div>
<div class="selectize-dropdown single liststyle" id="listitems"
style="display: None; width: 987px; top: 29px; left: 0px; visibility:
visible;">
<div class="selectize-dropdown-content">
{% block listplayers %}
{% if player is not None %}
{% for p in player %}
<div class="option selected curserstyle sp" id="{{p.id}}" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}1</div>
<div class="option selected curserstyle sp" id="49" data-selectable="" data-value="{{p.YourName}}">{{p.YourName}}2</div>
{% endfor %}
{% else %}
<div class="text-center">
List is Empty
</div>
{% endif %}
{% endblock %}
</div>
</div>
</div>
javascript
$("#listitems").on('click',function(e){
// preventing from page reload and default actions
e.preventDefault();
// serialize the data for sending the form data.
var serializedData = $(this).serialize();
// make POST ajax call
$.ajax({
type:'get',
url:"/templates/dashboard/players",
data:serializedData,
success:function(responce){
// on successfull creating object
// 1. clear the form.
$("#listitems").trigger('reset');
// 2. focus to nickname input
$(".sp").focus();
// display the newly friend to table.
var instance = JSON.parse(response["instance"]);
var fields = instance[0]["fields"];
var x = document.getElementById(user_id).textContent;
$("#playername").append('<div class="row list-row player-row " id="targetdel'+i+'"><div class="col-md-6 title"><a id="playername" href="#">'+x+'</a></div><div class="col-md-2 company text-center has-checkbox"><label class="green checkbox-box"><input type="checkbox" class="checkbox_entity checkbox_captain" id="captain" data-entity_id="17270" data-entity_type="captain" data-url_ajax="update_team_player"><span class="checkmark"></span></label></div> <div class="col-md-2 company text-center has-checkbox"> <label class="green checkbox-box "><input type="checkbox" class=" checkbox_entity checkbox_observer " id="cd_btn" data-entity_id="'+i+'" data-entity_type="observer" data-url_ajax="update_team_player style="background-color:black;" "> <span class="checkmark"></span> </label></div><div class="col-md-2 actions company text-right"><a href="" class="remove_entity_data" data-entity_id="17270" data-entity_type="team_player" > </a><button id = "'+i+'" class="btn del" style="text-transform: none;background-color: #ed143d00;padding: 0px 9px;border: none;color: #a2a2a2;">x</button></div></div>');
i++;
},
error: function (response) {
// alert the error if any error occured
alert("this one is error");
alert(response["responseJSON"]["error"]);
},
})
})
Apart from you using response in the success of the ajax when you have function(responce), you may be using the slim build of Jquery.
You should make sure you are using the full version of Jquery as the slim build for some reason does not have ajax included in it.
An easy way to check is to go to where you have defined your scripts and see whether your script has slim in it.
This is, I believe, the latest full version of jquery. This is what you should have.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
not this
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
I am new to Browserify but I think I am missing something. From what I can tell I have to load every single module for my app into bundle.js but I am totally lost as to how to call functions, objects etc for specific pages.
For instance, this is my main.js file:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
The mainUI(); bit is fine, as I need that to execute on every page to make my sidebar to work.
However, foodGrid is something that I only want to load when I visit the food page. If I do:
var bootstrap = require('bootstrap');
var mainUI = require('./main-ui');
var foodGrid = require('./food-grid');
mainUI();
foodGrid();
Then foodGrid() is called on every page, this is not correct.
foodGrid() is defined as:
module.exports = function () {
console.log('Test');
})
I can not see a way of getting this to work since everything is bundled into bundle.js, without doing some logic around the functions to determine if the user is on a certain page, which seems ridiculous.
My food page is:
#extends('layouts.master')
#section('title')
Enquiries
#stop
#section('body')
<div class="row">
<div class="col-xs-12">
<h3>Food</h3>
</div>
</div>
<div id="food_controls" class="row">
<div class="col-xs-9">
Control
</div>
<div class="col-xs-3">
<div class="input-group">
<span class="input-group-addon"><img width="20" src="{!!asset('images/loader.gif')!!}"><i class="fa fa-search"></i></span>
<input class="form-control" type="text" placeholder="Start typing to search...">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div id="foodGrid"></div>
</div>
</div>
#stop
#section('js')
{!! HTML::script('js/libs/kendo.all.min.js') !!}
<script>
enquiriesGrid();
</script>
#stop
The above gives me the error that foodGrid() is undefined.
Can someone tell me how to work with this? I must being missing something big.
(I am using Laravel 5, that is what all that blade syntax is)
elixir(function(mix) {
mix.browserify('main.js');
});
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.