I have a Flask-based web app. I already have a page with JQuery that works very well.
Now, I want to replace JQuery with Brython.
I have the following Brython code, which is not responding. I.e., it is not working as expected.
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<script type = "text/javascript" src = "https://cdn.jsdelivr.net/npm/brython#3.8.9/brython.min.js"></script>
<script type="text/python">
from browser import document, ajax, websocket
import json
global socket
# sending a connect request to the server
socket = new websocket("http://" + window.location.host + "/test")
# on page load
def on_load(event):
socket.send(json.dumps({'first_message': 'Hello World!'})) # send a message on page load
document["body"].bind("load", on_load)
# handle the response from the server
def handle_message(event):
msg = json.loads(event.data)
if 'get_jobs_as_list' in msg:
create_table(msg['rows'], msg['users'])
socket.bind("message", handle_message)
def create_table(row_count, users):
table_body = document["table1"].select("tbody")[0]
table_body.html = ""
for i in range(row_count):
markup = "<tr>" \
+ "<td>{}</td>".format(users[i]['job_id']) \
+ "<td>{}</td>".format(users[i]['unique_job_key']) \
+ "<td>{}</td>".format(users[i]['user_name']) \
+ "<td>{}</td>".format(users[i]['input_string']) \
+ "<td>{}</td>".format(users[i]['is_done']) \
+ "<td>{}</td>".format(users[i]['created_at']) \
+ "</tr>"
table_body <= markup
# handle the submit button click
def handle_submit(event):
text1 = document["text1"].value
text_area1 = document["text_area1"].text
socket.send(json.dumps({'text1': text1, 'text_area1': text_area1}))
document["button2"].bind("click", handle_submit)
</script>
</head>
<body onload="brython()">
<h1 id="h11">Header1</h1>
<h3 id="h33">description of app... ... ...</h3>
<h2 id="h22">Submit new job</h2>
<hr>
<table class="table table-striped">
<tr>
<td>Project-name :</td>
<td><input id="text1" type="text" value="username 9999" class="form-control" size="10"></td>
</tr>
<tr>
<td>Sequence :</td>
<td><textarea id="text_area1" class="form-control" size="10">protein string.12345</textarea></td>
</tr>
<tr>
<td>Secondary structure :</td>
<td><textarea id="text_area2" class="form-control" size="10">protein string.12345</textarea></td>
</tr>
<tr>
<td>Submit task:</td>
<td><input id="button2" type="button" value="Submit" class="btn btn-mini btn-primary">
<button type="reset" class="btn btn-inverse" onClick="clearFiles();"><i class="icon-repeat icon-white"></i> Clear form</button>
</td>
</tr>
</table>
<hr>
<table id="table1" class="table table-striped">
<thead>
<tr>
<th>Job ID</th>
<th>Job Key</th>
<th>User</th>
<th>Input String</th>
<th>Is Done?</th>
<th>Created At</th>
</tr>
</thead>
<tbody>
<tr>
<td>Job ID</td>
<td>Job Key</td>
<td>User</td>
<td>Input String</td>
<td>Is Done?</td>
<td>Created At</td>
</tr>
</tbody>
</table>
</body>
</html>
On the above page, when I click submit, nothing happens.
.
The following is the equivalent JQuery code:
<script>
// sending a connect request to the server.
let socket = io.connect('/test');
//on page load
$(function(){
socket.emit('first_connect_event', {'first_message' : 'Hello World!'});//send a message on page load
socket.on('get_jobs_as_list', function (msg){
let row_count = msg['rows'];
let json_users = $.parseJSON(msg['users']);
create_table(row_count, json_users);
});
function create_table(row_count, json_users)
{
let table_body = $("#table1 tbody");
table_body.empty();
let markup = '';
for(let i=0 ; i<row_count ; i++)
{
markup = "<tr>"
+ "<td>" + json_users[i]['job_id'] + "</td>"
+ "<td>" + json_users[i]['unique_job_key'] + "</td>"
+ "<td>" + json_users[i]['user_name'] + "</td>"
+ "<td>" + json_users[i]['input_string'] + "</td>"
+ "<td>" + json_users[i]['is_done'] + "</td>"
+ "<td>" + json_users[i]['created_at'] + "</td>"
+"</tr>";
table_body.append(markup);
}
return 99;
}
$('#button2').on('click', function(){
let text1 = $('#text1').val();
let text_area1 = $('#text_area1').text();
socket.emit('submit_task_event', {'text1' : text1, 'text_area1': text_area1});
});
});
</script>
This code is working fine.
Why is the Brython script not responding?
app.py
from flask import Flask, render_template, jsonify
from flask_socketio import SocketIO, emit
from PersistanceUtils import *
async_mode = None
app = Flask(__name__)
socketio_obj = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
# end if
#socketio_obj.on('first_connect_event', namespace='/test')
def handle_first_connect_event(arg1):
try:
msg = arg1['first_message']
print(msg)
rows, users = PersistanceUtils.get_jobs_as_json()
print(rows)
# print(users)
emit('get_jobs_as_list', {'rows': str(rows), 'users': str(users)})
except Exception as ex:
logging.exception("")
print(ex)
#socketio_obj.on('submit_task_event', namespace='/test')
def handle_submit_task_event(arg1):
try:
user_name1 = arg1['text1']
the_input_text1 = arg1['text_area1']
print(user_name1, the_input_text1)
PersistanceUtils.save_job_http(user_name1, the_input_text1)
rows, users = PersistanceUtils.get_jobs_as_json()
print(rows)
emit('get_jobs_as_list', {'rows': str(rows), 'users': str(users)})
except Exception as ex:
logging.exception("")
print(ex)
if __name__ == '__main__':
socketio_obj.run(app, debug=True)
Related
I´m done in updating the cell and now I want to refresh automatically the tag after i click the button looped by on the table using google-app-script. Cannot understand the coding in the documentation. Please help me to solve this. Thanks!
html
<div id="tables">
<? var data = getData();?>
<table id="tableShift1">
<caption style="">Shift1</caption>
<th> ID </th>
<th> Ldap </th>
<th> Action </th>
<? for (var dataList = 1; dataList < data.length; dataList++) {
if (data[dataList][2] == '') {?>
<tr >
<td><?= data[dataList][0] ?></td>
<td><?= data[dataList][1] ?></td>
<td><button onclick='google.script.run.setApproved("<?=data[dataList][0]?> ","<?=data[dataList][1]?>")' id='btnApprove'>Approve</button></td>
</tr>
<? }
} ?>
</table>
<table id="tableShift2">
<caption>Shift2</caption>
<th> ID </th>
<th> Ldap </th>
<th> Action </th>
</table>
</div>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
// The code in this function runs when the page is loaded.
$(function() {
google.script.run.withSuccessHandler(showData)
.getData();
});
function showData(things2) {
var table = $('#tableShift2');
var kwit = ',';
for (var i = 1; i < things2.length; i++) {
table.append('<tr ><td>' + things2[i][0] +
'</td><td style=>' + things2[i][1]+ things2[i][0] +
'</td><td ><button onclick="google.script.run.setApproved("'+ things2[i][0] +'","'+ things2[i][1] +'")" id="btnApprove">Approve</button></td></tr>');
}
}
</script>
</body>
You might try something like this:
Add and new function that provides the ability to return new data to refreshData()
function showData(things2) {
var table = $('#tableShift2');
var kwit = ',';
for (var i = 1; i < things2.length; i++) {
table.append('<tr ><td>' + things2[i][0] +
'</td><td style=>' + things2[i][1]+ things2[i][0] +
'</td><td ><button onclick="ApproveAndRefresh("'+ things2[i][0] +'","'+ things2[i][1] +'");" id="btnApprove">Approve</button></td></tr>');
}
}
function ApproveAndRefresh(data1,data2){//you may need to include i
google.script.run
.withSuccessHandler(refreshData)
.setApproved1(data1,data2);//a modified setApproved on the server that returns the appropriate html to the tableShift2 element
}
function refreshData(hl){
document.getElementById('tableShift2').innerHTML=hl;
}
It's been a long time since I coded so I am facing troubles.
I am using VS2015 .NET c# webForms Application. I have a simple form where the user need to fill a dynamic table and after hitting submit the values are passed to code behind for some calculation then stored in DB.
I used the HTML table in the link http://talkerscode.com/webtricks/add-edit-and-delete-rows-from-table-dynamically-using-javascript.php
the output:
I cant use Gridview becuase it postsback and connects to DB directly. I dont want to store the input of the table immediately.
I am stuck at retrieving the data from HTML table.
Can I get some hints or suggest to me any other better way to do if any.
If you want I can provide the code.
Thanks
UPDATE:
my code
form.aspx
<form runat="server">
//elements here
<div class="table-responsive" id="div_invlv">
<!------TABLE ---->
<table id="data_table" class="table" >
<tr>
<th></th>
<th> </th>
<th>Name</th>
<th>Position</th>
<th>Company</th>
<th></th>
</tr>
<tr>
<td>
<select class="form-control" id="type_of_person">
<option>Internal</option>
<option>External</option>
</select> </td>
<td><input type="text" class="form-control" id="new_name" /></td>
<td><input type="text" class="form-control" id="new_position" /></td>
<td><input type="text" class="form-control" id="new_company" /></td>
<td><input type="button" class="btn btn-small btn-template-main add" onclick="add_row();" value="Add Row" /></td>
</tr>
</table>
</form>
Table.js
function delete_row(no)
{
document.getElementById("row"+no+"").outerHTML="";
}
function add_row()
{
var drop = document.getElementById("type_of_person");
var new_type = drop.options[drop.selectedIndex].innerHTML;
var new_name=document.getElementById("new_name").value;
var new_country=document.getElementById("new_position").value;
var new_company=document.getElementById("new_company").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='id_row" + table_len + "'><asp:Label Name='id" + table_len + "' runat='server' > " + table_len + "</asp:Label></td> <td id='Type_row" + table_len + "'><asp:Label ID='type" + table_len + "' runat='server' > " + new_type + "</asp:Label></td><td id='name_row" + table_len + "'> <asp:Label ID='name'"+table_len+" runat='server' >" + new_name + "</asp:Label></td><td id='position_row" + table_len + "'>" + new_country + "</asp:Label></td><td id='company_row" + table_len + "'><asp:Label ID='company'"+table_len+" runat='server' >" + new_company + "</asp:Label></td><td > <input type='button' value='Delete' class='btn btn-small btn-template-main delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_name").value="";
document.getElementById("new_position").value = "";
document.getElementById("new_company").value = "";
}
C#
string typeTable = Request.Form["type" + 1];
Label10.Text = typeTable ;
The rows are generated during the run and I am trying to retrieve the value of one cell in the first row for testing but its not working.
The link provided by #legends
https://www.aspsnippets.com/Articles/Dynamically-Add-Rows-to-GridView-using-JavaScript-on-Button-Click-in-ASPNet.aspx
works great and solved most of my issue.
Thanks
you can use this function to fill your datagrid dyamically
public void fillgrid(string qry, GridView dg){
try
{
sql.cmd = new SqlCommand("qry", sql.cn);
sql.cn.Open();
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sql.cmd);
sda.Fill(ds);
dg.DataSource = ds;
dg.DataBind();
sql.cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
or you can use a placeholder control to create a dyamic html table
I have a table built dynamically in my view, I populated a table with values from a jquery popup modal dialog. What i am trying to accomplish is getting each cell in the row and assigning it to variable, at which point I am going to post the data to the database via an ajax call
I am fairly new to JS and jnquery and following many examples, I cant seem to figure out to assign the cell values to the variable, I have included the code below.
Here is the html for the table
<div class="row">
<div class="col-md-12">
<table id="myTest" class="table table-responsive">
<thead>
<tr>
<th>Sku Number</th>
<th>Product Name</th>
<th style="width:300px">Description</th>
<th>Quantity</th>
<th>Border</th>
<th>Ink Color</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div style="padding:10px 0; text-align: right; ">
<input id="submit" type="button" value="Save Order" class="btn btn-warning" style="padding: 10px 20px; margin-right: 15px;" />
</div>
</div>
Here is the JS for populating the table
function addItem() {
var remove = $('<input type="button" id="remove" value="remove" style="width:80px" class="btn btn-danger" />');
var td = $("<td></td>");
td.append(remove);
var valid = true;
allFields.removeClass("ui-state-error");
if (valid) {
$("#myTest tbody").append(
"<tr>" +
"<td>" + skuNumber.val() + "</td>" +
"<td>" + productName.val() + "</td>" +
"<td>" + description.val() + "</td>" +
"<td>" + quantity.val() + "</td>" +
"<td>" + border.val() + "</td>" +
"<td>" + inkColor.val() + "</td>" +
"</tr>");
dialog.dialog("close");
$("#myTest > tbody tr:last").append(td);
//console.log(td);
}
return valid;
}
And when you hit the submit button I want to create a list of objects that contains each row in the table, and this is where I am having problems.
$("#submit").click(function () {
var isAllValid = true;
var list = [];
$("#myTest tbody tr td")
.each(function(index, ele) {
var orderItem = {
SkuNumber: skuNumber.val(),
ProductName: productName.val(),
Description: description.val(),
Quantity: quantity.val(),
Border: border.val(),
InkColor: inkColor.val()
};
list.push(orderItem);
console.log(orderItem);
});
I using footable plugin for my projects.
But ,Its not working startly with phone screen.
Firstly i change screen size from chrome developer tools its workly fine like this,
but its not working when my codes rework on the phone screen.so like this
My html code ;
<div id="tablelistDiv">
<div class="row">
<table id="tbl_search" class="footable" data-page-size="20">
<thead>
<tr>
<th data-toggle="true" data-sort-ignore="false">Sıra No</th>
<th data-sort-ignore="false">Ünvan</th>
<th data-hide="phone" data-sort-ignore="false">Şube</th>
<th data-hide="phone" data-sort-ignore="false">Broker</th>
<th data-hide="phone" data-sort-ignore="false">Durum</th>
<th data-hide="phone" data-sort-ignore="false">Kayıt Tar.</th>
<th data-hide="phone" data-sort-ignore="true"><i class="fa fa-search"></i></th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td colspan="7">
<div class="pagination pagination-centered hide-if-no-paging"></div>
</td>
</tr>
</tfoot>
</table>
</div>
</div>
My Js Code is,
function detayKayitlar(jsondata, status) {
obj = JSON.parse(jsondata);
var tableHtml = "";
for (var i = 0; i < obj.length; i++) {
tableHtml = tableHtml
+ "<tr>"
+ "<td>" + obj[i].ID + "</td>"
+ "<td>" + obj[i].UNVAN + "</td>"
+ "<td>" + obj[i].SUBE + "</td>"
+ "<td>" + obj[i].BROKER + "</td>"
+ "<td>" + obj[i].USERLASMA + "</td>"
+ "<td>" + obj[i].KAYITTAR + "</td>"
+ "<td><button onclick='detayKayit(" + obj[i].ID + ",2);' class='btn btn-block btn-danger' type='button'><i class='fa fa-search'></button></td>"
+ "</tr>";
}
$("#tbl_search tbody").append(tableHtml);
jQuery(function () {
jQuery('#tbl_search').footable();
});
pWaitHide();
hideDiv('search');
showDiv('list');
}
Since your chrome is in desktop, it is working fine. Please check weather you have added the below line in your header tag or not. This view port will detect the screensize.
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
what do you mean with rework? if you doing something dynamically you
can run $('#tbl_search').trigger('footable_redraw');
from #Almis on first row comment.
Thank you
Really stupid question here, but I'm trying to display some JSON data in an HTML page. I'm more of a backend person (Bash) and only know basic HTML. I'd like to perform the Bash equivalent of storing data into a variable and calling it again later. Can I do that with Javascript/HTML? I have the rough code below, but I'd like to return some data in different points all over the page, not just in a list.
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<div id="placeholder"></div>
<script>
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$( "body" )
.append("Network: " + response.data.network + "<br/>" )
.append("Price: " + response.data.prices[0].price + "</br>")
.append("Exchange: " + response.data.prices[0].exchange+ "</br>")
.append("Price: " + response.data.prices[1].price + "</br>")
.append("Exchange: " + response.data.prices[1].exchange+ "</br>")
.append("Price: " + response.data.prices[3].price + "</br>")
.append("Exchange: " + response.data.prices[3].exchange+ "</br>");
}, "json" );
</script>
</body>
</html>
For example, I'd like to show the data at different points in the page. Is that possible?
<!DOCTYPE html>
<html>
<body>
<h2>Heading1</h2>
<ul style="list-style-type:disc">
<li>Test1</li>
<li>**JSON DATA HERE**</li>
<li>Test3</li>
</ul>
<h2>Heading2</h2>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>Thing1</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
<tr>
<td>Thing2</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
<tr>
<td>Thing3</td>
<td>**JSON DATA HERE**</td>
<td>**JSON DATA HERE**</td>
</tr>
</table>
</body>
</html>
Many ways this could be achieved. Example:
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$("#network").text(response.data.network);
$.each(response.data.prices, function(i, val) {
$("#thing" + i + "price").text(val.price);
$("#thing" + i + "exchange").text(val.exchange);
});
}, "json" );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Heading1</h2>
<ul style="list-style-type:disc">
<li>Test1</li>
<li><span id="network"></span></li>
<li>Test3</li>
</ul>
<h2>Heading2</h2>
<table>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
</tr>
<tr>
<td>Thing1</td>
<td><span id="thing0price"></span></td>
<td><span id="thing0exchange"></span></td>
</tr>
<tr>
<td>Thing2</td>
<td><span id="thing1price"></span></td>
<td><span id="thing1exchange"></span></td>
</tr>
<tr>
<td>Thing3</td>
<td><span id="thing2price"></span></td>
<td><span id="thing2exchange"></span></td>
</tr>
</table>
if I understand it correct, from your example, you can populate that data in your heading and table as follows
$.get( "https://chain.so/api/v2/get_price/BTC/USD", function( response ) {
$( "ul > li" )[1].html(response.data.network);
var tableHtml = '';
var prices = response.data.prices;
for(i=0;i<prices.length;i++){
tableHtml += '<tr>';
tableHtml += '<td>Thing '+i+'</td>';
tableHtml += '<td>'+prices[i].price +'</td>';
tableHtml += '<td>'+prices[i].exchange +'</td>';
tableHtml += '</tr>';
}
$('<table>').remove();//To remove any old table
$('<table>'+tableHtml+'</table>').insertAfter('h2');
}, "json" );