Initially I had everything working with Chosen plugin when the options were directly passed from python to the html template.
I then tried to make the options filled dynamically depending on one of the buttons clicked, the options were not rendered so nothing showed up (but if I inspect the Elements, each optgroup was filled correctly with options).
And if I remove $(".chosen-select").chosen() , then the options are rendered.
Here's my code:
<!-- language: html -->
<div class="container" style="margin:auto; padding-top: 2%; text-align: center;">
<b>Choose the Program:</b>
<ul id="programs" class="no-bullets" data-tag="programList">
<li onclick="selectProgram(this)">Type1</li>
<li onclick="selectProgram(this)">Type2</li>
<li onclick="selectProgram(this)">Type3</li>
</ul>
<b>Choose the Documents:</b>
<select id="documentOptions" name="documents" data-placeholder="Your Documents" class="chosen-select" multiple>
<optgroup label="Group1" id="Group1"></optgroup>
<optgroup label="Group2" id="Group2"></optgroup>
<optgroup label="Group3" id="Group3"></optgroup>
</select>
</div>
<!-- language: lang-js -->
<script>
$(".chosen-select").chosen()
function selectProgram(el){
Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="programList"] li')).forEach(function(element){
element.classList.remove('selected');
});
el.classList.add('selected');
programSelected = el.innerText;
//console.log(programSelected);
fetch(`/api/data/get_program/${programSelected}`)
.then(function(response){
return response.json();
}).then(function(documentList){
documentListJSON = {"documents":documentList};
//console.log(documentListJSON);
$.ajax({
type: 'POST',
url: '/api/data/programDocuments',
contentType: 'application/json',
data: JSON.stringify(documentListJSON),
success: function( allDocuments ){
console.log(allDocuments);
const Type1_Options = document.getElementById("Group1");
const Type2_Options = document.getElementById("Group2");
const Type3_Options = document.getElementById("Group3");
Type1_Options.innerHTML = "";
Type2_Options.innerHTML = "";
Type3_Options.innerHTML = "";
let docs_type1 = allDocuments['type1'];
let docs_type2 = allDocuments['type2'];
let docs_type3 = allDocuments['type3'];
// create list of options
var options = "";
for(var i = 0; i<docs_type1.length;i++){
options += "<option value='" + docs_type1[i] +"'>" + docs_type1[i] + "</option>";
}
Type1_Options.innerHTML += options;
$(Type1_Options).appendTo('#Group1');
var options = "";
for(var i = 0; i<docs_type2.length;i++){
options += "<option value='" + docs_type2[i] +"'>" + docs_type2[i] + "</option>";
}
Type2_Options.innerHTML += options;
$(Type2_Options).appendTo('#Group2');
var options = "";
for(var i = 0; i<docs_type3.length;i++){
options += "<option value='" + docs_type3[i] +"'>" + docs_type3[i] + "</option>";
}
Type3_Options.innerHTML += options;
$(Type3_Options).appendTo('#Group3');
}
})
})
}
</script>
I'm quite new to JavaScript and Jquery..Could someone please help explain why this happens?
Any help is very much appreciated. Thank you!
Related
am creating a searchable repository that displays heatmap after the search is completed in django (windows) and postgresql.
my code for the search is not used to HTML.
views.py
def search_result(request):
if request.method == "POST":
ChemSearched = request.POST.get('ChemSearched')
tarname = Bindll.objects.filter(targetnameassignedbycuratorordatasource__contains=ChemSearched)[:10]
return render(request, 'Search/search_result.html',
{'ChemSearched':ChemSearched,'tarname':tarname})
else:
return render(request, 'Search/search_result.html',{})
Searchresults.html
...
<br/><br/><br/><br/>
<strong><h1>{% if ChemSearched %}
<script>
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 450 - margin.left - margin.right,
height = 450 - margin.top - margin.bottom;
var svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
{% for Bindll in tarname %}
var myGroups = [ "{{ Bindll }}" ]
var myVars = [ "{{ Bindll.ki_nm }}" ]
{% endfor %}
var x = d3.scaleBand()
.range([ 0, width ])
.domain(myGroups)
.padding(0.01);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
var y = d3.scaleBand()
.range([ height, 0 ])
.domain(myVars)
.padding(0.01);
svg.append("g")
.call(d3.axisLeft(y));
var myColor = d3.scaleLinear()
.range(["white", "#69b3a2"])
.domain([1,100])
d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/heatmap_data.csv", function(data) {
svg.selectAll()
.data(data, function(d) {return d.group+':'+d.variable;})
.enter()
.append("rect")
.attr("x", function(d) { return x(d.group) })
.attr("y", function(d) { return y(d.variable) })
.attr("width", x.bandwidth() )
.attr("height", y.bandwidth() )
.style("fill", function(d) { return myColor(d.value)} )
})
</script>
<br>
{% for Bindll in tarname %}
{{ Bindll }}--{{ Bindll.ki_nm }}-{{ Bindll.ic50_nm }} - {{ Bindll.kd_nm }} - {{ Bindll.ec50_nm }} - <br>
{% endfor %}
{% else %}
<strong>No Entry</strong>
{% endif %}
never used webs before so any help why the chart is only showing one element, tried using for loop to append the values in a list did not work
but its printing quite fine the results, any way you can guide me on what am doing wrong, to make the heatmap show my results.
Thanks
Can you build your scale domains this way instead, and see if it works. I don't see the immediate problem outside of a possible mistake in the domains:
var myGroups= data.map(d=>d.group).filter((item, i, ar) => ar.indexOf(item) === i),
myVars = data.map(d=>d.variable).filter((item, i, ar) => ar.indexOf(item) === i);
I used Gridelements a while now. I used the following code:
TypoScript (Gridelements (deprecated) (gridelements)):
tt_content.gridelements_pi1.20.10.setup {
2col < lib.gridelements.defaultGridSetup
2col.cObject = FLUIDTEMPLATE
2col.cObject.file = {$resDir}/Private/Partials/Gridelements/2spalten.html
}
FLUID Template:
<div class="row">
<div class="col-md-6">
{data.tx_gridelements_view_column_0}
</div>
<div class="col-md-6">
{data.tx_gridelements_view_column_1}
</div>
</div>
PageTS:
tx_gridelements.setup {
2col {
title = Two Columns
config {
colCount = 2
rowCount = 1
rows {
1 {
columns {
1 {
name = Links
colPos = 0
}
2 {
name = Rechts
colPos = 1
}
}
}
}
}
}
}
But now I want to use "Gridelements w/DataProcessing (recommended) (gridelements)" because the other one is deprecated. But all I see is the error:
Tried resolving a template file for controller action "Standard->2col"
in format ".html", but none of the paths contained the expected
template file (Standard/2col.html). The following paths were checked:
/var/www/html/typo3/sysext/fluid_styled_content/Resources/Private/Templates/,
/var/www/html/typo3/typo3conf/ext/gridelements/Resources/Private/Templates/,
/var/www/html/typo3/typo3conf/ext/dev_layout/Resources/Private/Templates/
If I write this in my TypoScript code:
lib.gridelements.defaultGridSetup =< lib.contentElement
lib.gridelements.defaultGridSetup {
templateRootPaths {
20 = {$resDir}/Private/Templates/Gridelements/
}
}
tt_content.gridelements_pi1 < lib.gridelements.defaultGridSetup
tt_content.gridelements_view < tt_content.gridelements_pi1
And when I create the named file, the error no longer appears. But there is no output. I see the divs but no content. How can I switch from deprecated gridelements to dataprocessing gridelements?
"The documentation is wrong you need this"
tt_content.gridelements_pi1 =< lib.contentElement
Sure? I could still use the original as it is written in the example for w / DataProcessing:
lib.gridelements.defaultGridSetup =< lib.contentElement
The problem is that this code
tt_content.gridelements_pi1.20.10.setup {
2col < lib.gridelements.defaultGridSetup
2col.cObject = FLUIDTEMPLATE
2col.cObject.file = {$resDir}/Private/Partials/Gridelements/2spalten.html
}
does not match the new static you included.
Take a look at the basic example shown in the documentation:
https://docs.typo3.org/typo3cms/extensions/gridelements/stable/Chapters/DataProcessing/Index.html
lib.gridelements.defaultGridSetup =< lib.contentElement
lib.gridelements.defaultGridSetup {
templateName.field = tx_gridelements_backend_layout
templateName.ifEmpty = GridElement
layoutRootPaths {
1 = EXT:gridelements/Resources/Private/Layouts/
}
partialRootPaths {
1 = EXT:gridelements/Resources/Private/Partials/
}
templateRootPaths {
1 = EXT:gridelements/Resources/Private/Templates/
}
dataProcessing {
10 = GridElementsTeam\Gridelements\DataProcessing\GridChildrenProcessor
10 {
default {
as = children
# Default options of the grid children processor
# Change them according to the needs of your layout
# Read more about it in the TypoScript section of the manual
# options {
# sortingDirection = ASC
# sortingField = sorting
# recursive = 0
# resolveFlexFormData = 1
# resolveBackendLayout = 1
# respectColumns = 1
# respectRows = 1
# }
}
}
}
}
Now if you want to add your own templates and rendering configurations you just need to add something in dataProcessing.10 like
dataProcessing {
10 = GridElementsTeam\Gridelements\DataProcessing\GridChildrenProcessor
10 {
2col {
as = columncontent
options {
resolveFlexFormData = 0
respectRows = 0
}
}
accordion {
as = accordionitems
options {
resolveFlexFormData = 0
respectRows = 0
respectColumns = 0
}
}
}
}
The name of the variables can still be children, but it might be more comfortable to deal with variable names matching then purpose of your template.
I found the solution:
Template:
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" data-namespace-typo3-fluid="true">
<div class="row">
<f:if condition="{children}">
<f:for each="{children.1}" as="column" key="columnNumber">
<div id="c{data.uid}-{columnNumber}" class="grid-column grid-column-{columnNumber} col-lg-6">
<f:for each="{column}" as="child">
<f:render partial="Child"
arguments="{data: child.data, children: child.children, options: options, settings: settings}" />
</f:for>
</div>
</f:for>
</f:if>
</div>
</html>
For two different cols
<div id="c{data.uid}-{columnNumber}" class="grid-column grid-column-{columnNumber} {f:if(condition: '{columnNumber} == 0', then: 'col-lg-3', else: 'col-lg-9')}">
My column numbers are left 0 and right 1
TS in dataprocessing.10:
2col {
as = children
options {
resolveChildFlexFormData = 0
}
}
}
The documentation is wrong you need this
tt_content.gridelements_pi1 =< lib.contentElement
TSconfig:
Default gridelements TSConfig
I got same error after i upgrade to latest TYPO3 10 version from Typo3 9 and include Gridelement (Recommended).
Tried resolving a template file for controller action "Standard->1" in format ".html", but none of the paths contained the expected template file (Standard/1.html). The following paths were checked:
Solution:
Rename gridelement template name with 1.html for gridelement uid=1
Change TS like:
tt_content.gridelements_pi1 {
templateRootPaths {
15 = EXT:site_config/Resources/Private/Templates/Extensions/Grid-Templates/
}
dataProcessing {
10 {
default {
options {
resolveFlexFormData = 1
resolveChildFlexFormData = 0
}
}
}
}
}
Inside Grid-Templates add your gridelement templates like 1.html, 2.html etc.
3) change template(HTML) code like this:
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" data-namespace-typo3-fluid="true">
<div class="row">
<f:if condition="{children}">
<f:for each="{children.1}" as="column" key="columnNumber">
<div id="c{data.uid}-{columnNumber}" class="grid-column grid-column-{columnNumber} col-lg-6">
<f:for each="{column}" as="child">
<f:render partial="Child"
arguments="{data: child.data, children: child.children, options: options, settings: settings}" />
</f:for>
</div>
</f:for>
</f:if>
</div>
</html>
I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!
I've created a session list that contains my products, i need to update the quantity of any product by increasing it amount, for that am using an HTML type="number" , i also created a function which take the changed amount and multiplying it value with the current quantity, so lets say the amount of the first product by default is 2 by increasing the number lets say 2 the product amount will become 4 and so on, also the price will be multiplied .
Here are the codes:
<th style="text-align: center;" class="amount-izd">{{value["amount"]}}</th>
<th style="text-align: center; width: 14%;">
<div class="block">
<input type="number" id="myNumber" value="1" min=1 data-amount='{{value["amount"]}}' data-pros='{{value["id"]}}' data-price='
{% if g.currency == "euro" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["euro"]).rsplit(".",1)[0]}}
{% elif g.currency == "dollar" %}
{{format_price(value["price"] * config.SITE_CURRENCIES["dollar"]).rsplit(".",1)[0]}}
{% else %}
{{format_price(value["price"] * config.SITE_CURRENCIES["ruble"]).rsplit(".",1)[0]}}
{% endif %}
'>
<label for="myNumber">qty</label>
</div>
</th>
JQuery codes:
$("input[type='number']").bind('keyup change click', function (e) {
if (! $(this).data("previousValue") ||
$(this).data("previousValue") != $(this).val()
)
{
var currentAmount = $(this).attr('data-amount');
var currentPrice = $(this).attr('data-price');
$(this).closest('tr').find('.amount-izd').text(parseInt(currentAmount) * $(this).val());
$(this).closest('tr').find('.price-izd').text(parseInt(currentPrice) * $(this).val());
$.ajax({
type: 'post',
url: '/standard-{{g.currency}}/profile/'+$(this).attr("data-pros")+'/update/price/' + parseInt(currentPrice) * $(this).val(),
cache: false
}).done(function(data){
if(data.error){
toastr.error(data.error)
}
});
$(this).data("previousValue", $(this).val());
} else {
}
});
And finally views.py :
#profile_route.route("/standard-<set_curr>/profile/cart/", methods=['GET','POST'])
#authorize
def cart_products():
if "cart" not in session:
return render_template("my-cart.html", display_cart = {}, total = 0)
else:
items = session["cart"]
dict_of_products = {}
total_price = 0
for item in items:
product = Goods.query.get(item)
total_price += product.price
if product.id in dict_of_products:
pass
else:
dict_of_products[product.id] = {"qty":1, "name":product.product_name, 'category':product.Category.name, "sizes": product.sizes, "hex_color":product.hex_color, "text_color":product.text_color, "material":product.material, "article":product.article, "price":product.price, "sort": product.sort, "amount": product.amount, 'slug':product.slug, 'public_id' : product.public_id, "id":product.id}
return render_template("my-cart.html", display_cart=dict_of_products, total = total_price)
#profile_route.route("/standard-<set_curr>/profile/<int:id>/update/price/<price>", methods=['GET','POST'])
#login_required
def update_price(id, price):
items = session["cart"]
dict_of_products = {}
for item in items:
product = Goods.query.get(item)
if product.id in dict_of_products:
dict_of_products[id]['price'] = price
return jsonify(success=dict_of_products[id]['price'])
return jsonify(error='No product found.')
If i changed the amount , in console i got a 500 error that says:
return jsonify(success=dict_of_products[id]['price'])
KeyError: 47
Please how to overcome this problem ?
Update:
I was wondering , is it possible to update any value of the dictionary by accessing it directly from JQuery ??
Hey anyone can help me with this problem ?
I have this issue with my code, two files:
1 - test.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sin tÃtulo</title>
<script>
var url = "getagentids.php?param=";
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('formality').value = results[0];
document.getElementById('fullname').value = results[1];
document.getElementById('sex').value = results[2];
document.getElementById('id').value = results[3];
document.getElementById('joindate').value = results[4];
document.getElementById('jobtitle').value = results[5];
document.getElementById('city').value = results[6];
document.getElementById('typeofsalary').value = results[7];
document.getElementById('contract_type').value = results[8];
}
}
function getagentids() {
var idValue = document.getElementById("email").value;
var myRandom=parseInt(Math.random()*99999999); // cache buster
http.open("GET", url + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function getHTTPObject() {
var xmlhttp;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject();
</script>
</head>
<body>
<form name="schform">
<table bgcolor="#dddddd">
<tbody>
<?php
echo $param;
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = "SELECT email FROM dbemployeekpw";
$db->setQuery($query);
$result = $db->loadObjectList();
$email = $result[0];
echo " <select size='1' name='email' id='email' onChange='getagentids()' required >
<option value=''> Seleccione </option>";
foreach($result as $email)
{
echo "<option value='".$email->email."'>".$email->email."</option>";
}
echo "</select>"
?>
<tr><td>Formality</td><td><input id="formality" type="text" name="formality"></td></tr>
<tr><td>Fullname</td><td><input id="fullname" type="text" name="fullname"></td></tr>
<tr><td>Sex</td><td><input id="sex" type="text" name="sex"></td></tr>
<tr><td>Id</td><td><input id="id" type="text" name="id"></td></tr>
<tr><td>Joindate</td><td><input id="joindate" type="text" name="joindate"></td></tr>
<tr><td>Jobtitle</td><td><input id="jobtitle" type="text" name="jobtitle"></td></tr>
<tr><td>City</td><td><input id="city" type="text" name="city"></td></tr>
<tr><td>Typesalary</td><td><input id="typeofsalary" type="text" name="typeofsalary"></td></tr>
<tr><td>Contract Type</td><td><input id="contract_type" type="text" name="contract_type"> </td></tr>
<tr><td><input size="60" type="reset" value="Clear"></td><td></td>
</tr>
</tbody></table>
</form>
</body>
</html>
and..
2 - getagentids.php
<?php
//$param = $_GET["param"];
include '../../../connect.php';
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
$db->setQuery($query);
$results = $db->loadObjectList();
foreach ( $results as $result )
{
$formality = $result->formality;
$fullname = $result->fullname;
$sex = $result->sex;
$id = $result->id;
$joindate = $result->joindate;
$jobtitle = $result->jobtitle;
$city = $result->city;
$typeofsalary = $result->typeofsalary;
$contract_type = $result->contract_type;
$textout = $formality.",".$fullname.",".$sex.",".$id.",".$joindate.",".$jobtitle.",".$city.",".$typeofsalary.",".$contract_type;
}
echo $textout;
?>
But ajax dont works, only works if I put this :
$query = "SELECT * FROM dbemployeekpw WHERE email = 'camilo.uribe#kantarworldpanel.com'";
instead this:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
But I need that the code works with second one :(
Anyone can help me with this problem ?
Thanks !!
SOLVED (works like a charm!!):
I change this:
$jinput = JFactory::getApplication()->input;
$param = $jinput->get('param', 'param', 'filter');
instead this:
$param = $_GET["param"];
and I'm still with:
$query = "SELECT * FROM dbemployeekpw WHERE email = '".$param."'";
because this code don't works for me:
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
Many Thanks #lodder
Before anything, lets see if the $param variable is correct and gets the value. Add the following which one the form is processed, will display the value. If the result is NULL then you firstly need to ensure you get the correct value. If you do get the correct value, then carry on reading.
Just on a side note, I would recommend looking at the following link rather than using $_GET:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Lets now use up to date coding standards for you database query:
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName('*'))
->from($db->quoteName('dbemployeekpw'))
->where($db->quoteName('email') . ' = '. $db->quote($param));
$db->setQuery($query);
$results = $db->loadObjectList();
Hope this helps