flask forms and javascript - javascript

hello i have the html code below
<form>
<input type="text" id="filepathz" size="40" placeholder="Spot your project files">
<input type="button" id="spotButton" value="Spot">
</form>
the javascript code
window.onload = init;
function init() {
var button = document.getElementById("spotButton");
button.onclick = handleButtonClick;
}
function handleButtonClick(e) {
var filepathz = document.getElementById("filepathz");
var path = filepathz.value;
if (path == "") {
alert("give a filepath");
}else{
var url = "http://localhost:5000/tx/checkme/filepathz=" + path;
window.open (url,'_self',false);
}
}
and the python code on flask
def index():
"""Load start page where you select your project folder
or load history projects from local db"""
from txclib import get_version
txc_version = get_version()
prj = project.Project(path_to_tx)
# Let's create a resource list from our config file
res_list = []
prev_proj = ''
for idx, res in enumerate(prj.get_resource_list()):
hostname = prj.get_resource_host(res)
username, password = prj.getset_host_credentials(hostname)
return render_template('init.html', txc_version=txc_version, username=username)
#app.route('/tx/checkme/<filepathz>')
def checkme(filepathz):
filepathz = request.args.get('filepathz')
return render_template('init.html', txc_version=filepathz)
what am i doing wrong and can't get the data from the form (filepathz) <--- i get None

You're not passing the variable correctly. There are two ways to pass the variable:
1) Pass it via get method:
http://localhost:5000/tx/checkme/?filepathz=" + path; (Note the '?')
Currently you are trying to get the variable from request.args but not passing it in the request, that's why you get none.
2) Get it from the url with flask's url structure:
Do this in JS : http://localhost:5000/tx/checkme/" + path
And in you view :
#app.route('/tx/checkme/<filepathz>')
def checkme(filepathz):
return render_template('init.html', txc_version=filepathz) # You can use this variable directly since you got it as a function arguement.

Related

how to make an Ajax request to a URL and append the url with query string in order to run the url program

I am trying to get information from a form without using a submit button. First I need to build a query string and then I need to make an ajax request to a URL that contains a program that will take the information from the forms to calculate the mileage from one city to the other. here is my http file:
<!DOCTYPE html>
<html>
<head>
<title>Mileage Calculator</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>Mileage Calculator</h1>
<form>
Start City<input type="text" id="startCity" name="startCity"></input><br><br>
Start State<input type="text" id="startState" name="startState"></input><br><br>
End City<input type="text" id="endCity" name="endCity"></input><br><br>
End State<input type="text" id="endState" name="endState"></input><br><br>
<input type="button" onclick="buildQuery()" value="Submit"></input>
</form>
<p id="justTry">Let's see if we can change this guy</p>
<script src="assign12.js"></script>
</body>
</html>
I am using an onclick event to call a javascript function that collects all the form info and arranges it into a query string. Here is that function "buildQuery()" :
function buildQuery() {
startcity = document.getElementById("startCity").value;
startstate = document.getElementById("startState").value;
endcity = document.getElementById("endCity").value;
endstate = document.getElementById("endState").value;
var params = {
startcity,
startstate,
endcity,
endstate
};
var esc = encodeURIComponent;
var query = Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
loadSite(query);
}
the buildQuery() function then calls the loadQuery(query) function which makes an ajax request. This is were I am having trouble. the query string must be appended to the URL so it can take the form info and calculate the mileage, but I'm not sure how to get that to happen. here is what I have so far:
function loadSite(query) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
appendQuery(this.responseText);
//document.getElementById("justTry").innerHTML = url;
}
};
var url = "/cgi-bin/ercanbracks/mileage/mileageAjaxJSON" + query;
xhttp.open("POST", "/cgi-bin/ercanbracks/mileage/mileageAjaxJSON", true)
xhttp.send();
}
what is the best way to accomplish this task?
thanks, Megan
First thing first, you should not manually select all the inputs with ids. Instead I would recommend selecting the inputs using querySelectorAll as below
function getFormPayload(formId){
const payload = {};
for(const input of document.querySelectorAll(`form#${formId} *[name]`)){
payload[input.getAttribute('name')] = input.value;
}
return payload;
}
With the function above you can then iterate through the value and create the query as you initially did.
p/s: Note that some elements like select doesn't have value attribute so you would need to wrap the value assign in an if statement. Good luck!

problem on using crystal report in MVC C# redirect aspx from controller

I using the sample code from this blog https://www.mysharings.com/coderblog/how-to-use-crystal-reports-in-asp-net-mvc/
It works OK, I can export my old crystal report to PDF. But it calls the aspx from javascript. I try to call it from the controller, it nothing gets exported even if debugging inside aspx.cs, after running though the code it's not exporting the PDF.
At the end both code samples will call objReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, response, true, fileName);
Since they redirect to the same aspx file and they are getting the same DataTable from mssql how come direct from javascript works but it fails on direct from controller? Any idea?
I try to use redirection , service.execute, and response.redirect but still got the same error.
I wondered if that is like that because I needed to add the attribute on reportframe from the controller so I used
var myDiv = new HtmlGenericControl("ReportFrame");
myDiv.Attributes.Add("src", path);
but it still does not work.
=========== code call from Javascript ========================================
<input id="report" type="submit" class="btn btn-primary" value="Report"
onclick="PrintReport('pdf'); />
<iframe id="ReportFrame" src="" width="100%" height="1000" style="display:none"></iframe>
function PrintReport(printType) {
if (printType == 'inline') {
//you can add the loading.....
}
//var params = "param1=;param2=";//create the parameters for report
var params = '';
//load the report by iframe
$("#ReportFrame").attr("src", "#Url.Content("~/Report/ReportViewer.aspx?
Params=")" + params + "&ReportName=PrintConsumerInfoBS&SaveName=Testing
Report&ReportType=" + printType + "&ReportPath=WebListReports");
$('#ReportFrame').load(function () {
//and stop the loading after load
});
}
===========================Code call from controller===========================
<input id="report" type="submit" class="btn btn-primary" value="Report"
/>
<iframe id="ReportFrame" src="" width="100%" height="1000" style="display:none"></iframe>
$('#report').click(function () {
var url = '/Consumer/ExportConsumer';
var formName = '#Consumerform';
Global.postData(formName, url)
})
and C#
public ActionResult ExportConsumer(ConsumerJson jsn)
{
//var Consumer = ConsumerAction.Report(jsn.c_uci);
var EmptyPara = "";
var reportType = "PDF";
var reportFolder = "WebListReports";
var reportName = "PrintConsumerInfoBS";
var path = "~/Report/ReportViewer.aspx?Params=" + EmptyPara.Trim()
+ "&ReportName=" + reportName.Trim()
+ "&SaveName="+ reportName.Trim()
+ "&ReportType=" + reportType.Trim()
+ "&ReportPath="+ reportFolder.Trim();
//var myDiv = new HtmlGenericControl("ReportFrame");
//myDiv.Attributes.Add("src", path);
Response.Redirect(path);
return ReturnConsumerProfile();
}
Nothing download or export call from controller

Get content inside of script tag

Hello everyone I'm trying to fetch content inside of script tag.
http://www.teknosa.com/urunler/145051447/samsung-hm1500-bluetooth-kulaklik
this is the website.
Also this is script tag which I want to enter inside.
$.Teknosa.ProductDetail = {"ProductComputedIndex":145051447,"ProductName":"SAMSUNG HM1500 BLUETOOTH KULAKLIK","ProductSeoName":"samsung-hm1500-bluetooth-kulaklik","ProductBarcode":"8808993790425","ProductPriceInclTax":79.9,"ProductDiscountedPriceInclTax":null,"ProductStockQuantity":1,"ProductMinStockQuantity":null,"ProductShortDescription":null,"ProductFullDescription":null,"ProductModelName":"HM1500","ProductAdminComment":null,"ProductMetaTitle":null,"ProductMetaKeywords":null,"ProductMetaDescription":null,"ProductBrandId":299,"ProductBrandName":"SAMSUNG","ProductBrandImageName":"//img-teknosa.mncdn.com/StaticContent/images/Brand/SAMSUNG-medium.png","ProductCommentCout":29,"ProductQuestionAnswerCout":0,"ProductRatingStar":4,"ProductType":1,"ProductOriginalComputedIndex":null,"ProductIsSolo":false,"ProductIsClickCollect":true,"ProductStoreStockAmount":1,"ProductGroupDisplayName":null,"ProductOrigin":"PRC","ProductIsTss":false,"ProductIsKit":false,"AddBasketButtonType":0,"ProductViewType":0,"ProductDetailDefaultPicture":"145051447-1-samsung-hm1500-bluetooth-kulaklik.jpg","ProductRatingStarText":"Çok İyi","ProductPrice":"79,9","IsThereOutletProduct":false,"ProductIsActiveProductOriginal":false,"ProductErpCatalogCode":"_TELEKOM","ProductErpCategoryCode":"_BLUETOOTH_KULAKLIKLAR1636","ProductCategory":{"CategoryName":"Bluetooth Kulaklık ve Kit","CategorySeoName":"bluetooth-kulaklik-ve-kit","CategoryDescription":null,"CategoryParentId":134,"CategoryLevel":2,"CategoryMetaTitle":null,"CategoryMetaKeywords":null,"CategoryMetaDescription":null,"Parent":{"CategoryName":"Telefon Aksesuarları","CategorySeoName":"telefon-aksesuarlari","CategoryDescription":null,"CategoryParentId":108,"CategoryLevel":1,"CategoryMetaTitle":null,"CategoryMetaKeywords":null,"CategoryMetaDescription":null,"Parent":{"CategoryName":"Telefon","CategorySeoName":"telefon","CategoryDescription":null,"CategoryParentId":null,"CategoryLevel":0,"CategoryMetaTitle":null,"CategoryMetaKeywords":null,"CategoryMetaDescription":null,"Parent":null,"DisplayOrder":6,"StatusId":100110,"StartDate":"\/Date(1434351061000)\/","EndDate":null,"Id":108},"DisplayOrder":3,"StatusId":100110,"StartDate":"\/Date(1434351245000)\/","EndDate":null,"Id":134},"DisplayOrder":3,"StatusId":100110,"StartDate":"\/Date(1434351367000)\/","EndDate":null,"Id":173},"ProductDetailPictures":[{"ProductPictureName":"145051447-1-samsung-hm1500-bluetooth-kulaklik.jpg","ProductPictureOrder":1,"ProductPictureIsDefault":true},{"ProductPictureName":"145051447-2-samsung-hm1500-bluetooth-kulaklik.jpg","ProductPictureOrder":2,"ProductPictureIsDefault":false}],"ProductDetailAttributes":[{"Key":"Ağırlık","Value":"18.1","UnitItemName":"gr","ProductAttributeDisplayOrder":0,"DisplayOrder":2,"Description":null},{"Key":"Model","Value":"HM1500","UnitItemName":null,"ProductAttributeDisplayOrder":0,"DisplayOrder":4,"Description":null},{"Key":"Şarj Kullanım Süresi","Value":"2 Saat","UnitItemName":null,"ProductAttributeDisplayOrder":0,"DisplayOrder":80,"Description":null},{"Key":"Bekleme Süresi (Saat)","Value":"250 Saat (Maks.)","UnitItemName":null,"ProductAttributeDisplayOrder":0,"DisplayOrder":116,"Description":null},{"Key":"Kullanım Mesafesi","Value":"10 m. (Maks.)","UnitItemName":null,"ProductAttributeDisplayOrder":0,"DisplayOrder":145,"Description":null},{"Key":"Bluetooth Profili","Value":"HSP (Kulaklık), HFP (Ahizesiz)","UnitItemName":null,"ProductAttributeDisplayOrder":0,"DisplayOrder":149,"Description":null}],"ProductSuggestions":[],"ProductContents":[],"ProductKitItems":[],"ProductVideos":[],"ProductGroups":[],"ProductBadges":[{"BadgeItemBadgeId":7,"BadgeItemApplicationId":1,"BadgeItemText":null,"BadgeItemImageName":"//img-teknosa.mncdn.com/StaticContent/images/Badge/ucretsiz-kargo.png","BadgeItemDescription":null,"BadgeItemPagePosition":"ImageBottom","BadgeItemImagePosition":null,"BadgeItemDisplayView":"ProductDetail","BadgeItemType":"Image","BadgeItemDynamicType":"WebStock","BadgeItemDynamicTypeText1":null,"BadgeItemDynamicTypeText2":null,"BadgeItemDynamicTypeCalculationType":null,"BadgeItemDynamicTypeDisplayType":null,"BadgeItemEvaluationExpression":null,"BadgeItemClassName":null,"DisplayOrder":0,"StatusId":100110,"StartDate":"\/Date(1474440397000)\/","EndDate":null,"Id":5}],"DisplayOrder":1000,"StatusId":100110,"StartDate":"\/Date(1429000863000)\/","EndDate":null,"Id":4715};
And I tried this.
yield scrapy.Request(response.urljoin(url), callback = self.parseProduct, meta={
'splash': {
'endpoint': 'render.html',
'args': {'wait': 0.09}},
'url': url
})
def parseProduct(self, response):
data_bundles = {}
script = response.xpath('/html/body/div[1]/div[2]/script[2]/text()').extract_first()
print script
jstree = js2xml.parse(script)
for a in jstree.xpath('//assign[left//property/identifier/#name="$.Teknosa.ProductDetail" and right/object]'):
bundle_prop = a.xpath('./left/bracketaccessor/property/string/text()')
print bundle_prop
if bundle_prop is not None:
curr_prop = bundle_prop[0]
data_bundles[curr_prop] = {}
Thanks for your help.
This should do it:
response.xpath("//script[re:test(text(),'Teknosa.ProductDetail =','i')]").extract()
You can select script tag that contains "Teknosa.ProductDetails =" in it's text.
Edit:
If you want to load up javascript dictionary from script you need to extract text from the script and you can simply load it up with python's json module.
xp = "//script[re:test(text(),'Teknosa.ProductDetail =','i')]/text()"
data = response.xpath(xp).re(" = (\{.+\})")[0]
import json
data = json.loads(data)
print(data['ProductBarcode'])
> '8808993790425'

Is that possible to put Template7 code in a separate file rather than in html

I am using a framework called Framework7.
In my index.html, I have some Template7 code, like this format
<script type="text/template7" id="commentsTemplate">
{{#each this}}
<div> test this template 7 code </div>
</script>
However, I want to have this part of code into an another separated file (Just like I can have many other *.js files in, say, a static folder and refer to the file by "static/*.js).
I have tried to use a typical way to import js
<script type="text/template7" id="storiesTemplate" src="js/template.js"></script>
But it doesn't work, there is also no demo/sample code in the documentation.
Any help is appreciated!
You can do it. The idea behind is to include a HTML file in a HTML file. I can tell at least 3 ways that this can happen, but personally I fully validated only the third.
First there is a jQuery next sample is taken from this thread
a.html:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("b.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
b.html:
<p> This is my include file </p>
Another solution, I found here and doesn't require jQuery but still it's not tested: there is a small function
My solution is a pure HTML5 and is probably not supported in the old browsers, but I don't care for them.
Add in the head of your html, link to your html with template
<link rel="import" href="html/templates/Hello.html">
Add your template code in Hello.html. Than use this utility function:
loadTemplate: function(templateName)
{
var link = document.querySelector('link[rel="import"][href="html/templates/' + templateName + '.html"]');
var content = link.import;
var script = content.querySelector('script').innerHTML || content.querySelector('script').innerText;
return script;
}
Finally, call the function where you need it:
var tpl = mobileUtils.loadTemplate('hello');
this.templates.compiledTpl = Template7.compile(tpl);
Now you have compiled template ready to be used.
=======UPDATE
After building my project for ios I found out that link import is not supported from all browsers yet and I failed to make it work on iphone. So I tried method number 2. It works but as you might see it makes get requests, which I didn't like. jquery load seems to have the same deficiency.
So I came out with method number 4.
<iframe id="iFrameId" src="html/templates/template1.html" style="display:none"></iframe>
and now my loadTemplate function is
loadTemplate: function(iframeId, id)
{
var iFrame = document.getElementById(iframeId);
if ( !iFrame || !iFrame.contentDocument ) {
console.log('missing iframe or iframe can not be retrieved ' + iframeId);
return "";
}
var el = iFrame.contentDocument.getElementById(id);
if ( !el ) {
console.log('iframe element can not be located ' + id );
return "";
}
return el.innerText || el.innerHTML;
}
How about lazy loading and inserting through the prescriptions?
(function (Template7) {
"use strict";
window.templater = new function(){
var cache = {};
var self = this;
this.load = function(url)
{
return new Promise(function(resolve,reject)
{
if(cache[url]){
resolve(cache[url]);
return true;
}
if(url in Template7.templates){
resolve(Template7.templates[url]);
return true;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(this.status == 200 && this.response.search('<!DOCTYPE html>') == -1){
cache[url] = Template7.compile(this.response);
resolve(cache[url]);
}else{
reject(`Template ${url} not found`);
}
};
xhr.send();
})
}
this.render = function(url, data)
{
return self.load(url)
.then(function(tpl){
return tpl(data) ;
});
}
this.getCache = function()
{
return cache;
}
}
})(Template7);
Using :
templater.render('tpl.html').then((res)=>{ //res string })
Or :
templater.load('tpl.html').then( tpl => { Dom7('.selector').html( tpl(data) ) } )
It is possible to define your templates in .js-files. The template just needs to be a string.
Refer to this [JSFiddle] (https://jsfiddle.net/timverwaal/hxetm9rc/) and note the difference between 'template1' and 'template2'
var template1 = $$('#template').html();
var template2 = '<p>Hello, my name is still {{firstName}} {{lastName}}</p>'
template1 just extracts the content of the <script> and puts it in a string.
template2 directly defines the string

How to stock my Mustache / Handlebars templates in separate files?

I'm using handlebars.js on a project and I'm starting to have a fair amount of templates.
For now they are stored in my main template app file, like this :
<script id="avatar_tpl" type="text/html">
bla bla bla {{var}} bla bla bla
</script>
I'm wondering if there is a way to put them in a separate file like a .js file or something, to avoid stacking them up in my source code page.
I'm aware that there are several solutions to call theses templates via Ajax, but that seems to result in too much unnecessary requests for me.
Thank you
I created and open-sourced NodeInterval for this exact same problem of too many js templates in my HTML page.
It allows you to put all your templates into a templates folder organized in whatever hierarchy you like. It has a built in watch capability so that as you modify any of these templates it automatically updates your HTML page. I use it alongside SASS for my CSS.
I use it daily with underscore templates but it should work fine with moustache templates as well:
https://github.com/krunkosaurus/NodeInterval
Couldn't you just include a js file with your templates as js variables? Not tested, just thinking here:
//in your html page
<script id="avatar_tpl" type="text/html" src="mytemplates.js"></script>
// then in your mytemplates.js file
var template_1 = "{{ content }}";
var template_2 = "{{ content }}";
// and you could use it like this back in html page
var template1 = Handlebars.compile(template_1);
var template2 = Handlebars.compile(template_2);
if you are using jquery, you could create an invisible div with id "template-holder"
then use :
$("#template-holder").load([url here])
to load the html into the div
then use :
var templatestr = $("#template-holder").find("#avatar_tpl").html()
to get the template
:)
I'm not familiar with handlebars.js but, have you tried this?:
<script id="avatar_tpl" type="text/html" src="myscript.html"></script>
I've been rolling all my scripts and templates in to one big .js file for several projects now. I use a java-based build tool, ant, to concatenate and manage various processing scripts for my js.
The biggest problem with storing large templates in javascript variables is javascript's lack of multi-line strings. I deal with this by writing my files with a python-like triple-quote syntax:
var templateVariable = '''
<div>
<div></div>
</div>
'''
I then run this custom-syntax javascript file though the python script included below, which turns it in to legal javascript:
#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Morgan Packard on 2009-08-24.
Copyright (c) 2009 __MyCompanyName__. All rights reserved.
"""
import sys
import os
def main():
f = open(sys.argv[1], 'r')
contents = f.read()
f.close
split = contents.split("'''")
print "split length: " + str(len(split))
processed = ""
for i in range(0, len(split)):
chunk = split[i]
if i % 2 == 1:
processedChunk = ""
for i,line in enumerate(chunk.split("\n")):
if i != 0:
processedChunk = processedChunk + "+ "
processedChunk = processedChunk + "\"" + line.strip().replace("\"", "\\\"").replace('\'', '\\\'') + "\"" + "\n"
chunk = processedChunk
processed = processed + chunk
f = open(sys.argv[1], 'w')
f.write(processed)
f.close()
if __name__ == '__main__':
main()
Working this way, I can code templates in more-or-less pure html, and deploy them, along with application code, inside a single .js file.
I created a Lazy Load javascript file that loads the templates only as needed. It's performing the AJAX calls, but seems to work quite well.
var Leuly = Leuly || {};
Leuly.TemplateManager = (function ($) {
var my = {};
my.Templates = {};
my.BaseUrl = "/Templates/";
my.Initialize = function (options) {
/// <summary>
/// Initializes any settings needed for the template manager to start.
/// </summary>
/// <param name="options">sets any optional parameters needed</param>
if (options && options.BaseUrl) {
my.BaseUrl = options.BaseUrl;
}
};
my.GetTemplate = function (templateName, success, baseUrl) {
/// <summary>
/// makes a request to retrieve a particular template
/// </summary>
/// <param name="templateName">name of the template to retrieve</param>
/// <param name="success">event returning the success</param>
var template = my.Templates[templateName];
if (template == null) {
template = my.LoadTemplate(templateName, success, baseUrl);
}
else {
success(template, true);
}
};
my.LoadTemplate = function (templateName, success, baseUrl) {
/// <summary>
/// makes a request to load the template from the template source
/// </summary>
/// <param name="templateName">name of the template to retrieve</param>
/// <param name="success">event returning the success</param>
var root = baseUrl == null ? my.BaseUrl : baseUrl;
$.get(root + templateName, function (result) {
my.Templates[templateName] = result;
if (result != null && success != null) {
success(result, true);
}
});
};
return my;
} (jQuery));
$(function () {
Leuly.TemplateManager.Initialize();
});

Categories

Resources