display data in the form of a table using Ajax - python

I have the below code in Ajax to display the data from python stored in MongoDB.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
alert(JSON.stringify(element));
});
});
});
}
</script>
Python call for the same:
#route('/ajax1')
def func():
client = MongoClient()
db = client.collection
result = db.collection.find({},{'_id':0}).limit(2)
arr = []
for document in result:
arr.append(doc)
return (dict(items=arr))
I am getting the result as below:
[{"Name":"abc","Place":"SomePlace","Designation":"des"}]
[{"Name":"NextName","Place":"NextPlace","Designation":"Nextdes"}]
I want to print it in this format or in the form of a table:
abc Someplace des
NextName Nextplace Nextdes
Can somebody tell me how to do it? Seems simple but I am unaware of it.
Thanks!

To me it would make more sense to use the property names in the javascript as it's easier to understand and more verbose.
<script>
function f(){
$(document).ready(function(){
$.get('ajax1', function(result){
$.each(result, function(index, element) {
var row = element.Name + " " + element.Place + " " + element.Designation;
console.log(row);
});
});
});
}
</script>

Related

Updating database after reordering Datatable

I'm struggling with the datatables reordering. I want when user reorder to update table in the database. For this to happen i need:
to configure the datatable to send request to the server.
send the information about reordered datatable to flask endpoint.
Process data on the backend and update database table.
I have read the documentation but it is not clear to me.
My code:
$(document).ready(function () {
var dt = $('#data').DataTable({
rowReorder: true,
dom: 'Bfrtip'
});
});
My own solution:
JavaScript code:
dt.on('row-reorder.dt', function (e, details, edit) {
var slownik = {};
for (var i = 0, ien = details.length; i < ien; i++) {
let id_asortymentu = details[i].node.id;
let nowa_pozycja = details[i].newPosition+1;
console.log(id_asortymentu);
console.log(nowa_pozycja);
slownik[id_asortymentu] = nowa_pozycja;
}
req = $.ajax({
url: 'asortymenty/tabela_reorder',
dataType: "json",
type: 'POST',
data : JSON.stringify(slownik)
});
req.done(function(data){
if (data.result == 1){
console.log('Table reordered.');
}
});
});
Flask backend code:
#admin.route('asortymenty/tabela_reorder', methods = ['GET','POST'])
def table_reorder():
slownik=request.get_json('data')
for key, value in slownik.items():
asort = Asortyment.query.get(key)
print(asort.pozycja)
asort.pozycja = value
db.session.add(asort)
db.session.commit()
return jsonify({'result' : '1'})

Problem dealing with a space when moving JSON to Python

I am high school math teacher who is teaching myself programming. My apologies in advance if I don't phrase some of this correctly.
I am collecting CSV data from the user and trying to move it to a SQLite database via Python.
Everything works fine unless one of the values has a space in it.
For example, here is part of my JavaScript object:
Firstname: "Bruce"
Grade: ""
Lastname: "Wayne Jr"
Nickname: ""
Here is the corresponding piece after applying JSON.stringify:
{"Firstname":"Bruce","Lastname":"Wayne Jr","Nickname":"","Grade":""}
This is then passed to Python via a form. In Python, I use:
data = request.form.get("data")
print(data)
data2 = json.loads(data)
print(data2)
I get a bunch of error messages, ending with: json.decoder.JSONDecodeError: Unterminated string starting at: line 1 column 250 (char 249) and the log of the first print gives:
[{"Firstname":"Jason","Lastname":"Bourne","Nickname":"","Grade":"10"},
{"Firstname":"Steve","Lastname":"McGarret","Nickname":"5-0","Grade":""},
{"Firstname":"Danny","Lastname":"Williams","Nickname":"Dano","Grade":"12"},
{"Firstname":"Bruce","Lastname":"Wayne
So it seems to break on the space in "Wayne Jr".
I used what I learned here to build the basics:
https://bl.ocks.org/HarryStevens/0ce529b9b5e4ea17f8db25324423818f
I believe this JavaScript function is parsing the user data:
function changeDataFromField(cb){
var arr = [];
$('#enter-data-field').val().replace( /\n/g, "^^^xyz" ).split( "^^^xyz" ).forEach(function(d){
arr.push(d.replace( /\t/g, "^^^xyz" ).split( "^^^xyz" ))
});
cb(csvToJson(arr));
}
Updates based on comments:
I am using a POST request. No AJAX.
There are actually 2 inputs for the user. A text box where they can paste CSV data and a file upload option. Here is some more of the JavaScript.
// Use the HTML5 File API to read the CSV
function changeDataFromUpload(evt, cb){
if (!browserSupportFileUpload()) {
console.error("The File APIs are not fully supported in this browser!");
} else {
var data = null;
var file = evt.target.files[0];
var fileName = file.name;
$("#filename").html(fileName);
if (file !== "") {
var reader = new FileReader();
reader.onload = function(event) {
var csvData = event.target.result;
var parsed = Papa.parse(csvData);
cb(csvToJson(parsed.data));
};
reader.onerror = function() {
console.error("Unable to read " + file.fileName);
};
}
reader.readAsText(file);
$("#update-data-from-file")[0].value = "";
}
}
// Method that checks that the browser supports the HTML5 File API
function browserSupportFileUpload() {
var isCompatible = false;
if (window.File && window.FileReader && window.FileList && window.Blob) {
isCompatible = true;
}
return isCompatible;
}
// Parse the CSV input into JSON
function csvToJson(data) {
var cols = ["Firstname","Lastname","Nickname","Grade"];
var out = [];
for (var i = 0; i < data.length; i++){
var obj = {};
var row = data[i];
cols.forEach(function(col, index){
if (row[index]) {
obj[col] = row[index];
}
else {
obj[col] = "";
}
});
out.push(obj);
}
return out;
}
// Produces table for user to check appearance of data and button to complete upload
function makeTable(data) {
console.log(data);
send_data = JSON.stringify(data);
console.log(send_data);
var table_data = '<table style="table-layout: fixed; width: 100%" class="table table-striped">';
table_data += '<th>First name</th><th>Last name</th><th>Nickname</th><th>Grade</th>'
for(var count = 0; count < data.length; count++) {
table_data += '<tr>';
table_data += '<td>'+data[count]['Firstname']+'</td>';
table_data += '<td>'+data[count]['Lastname']+'</td>';
table_data += '<td>'+data[count]['Nickname']+'</td>';
table_data += '<td>'+data[count]['Grade']+'</td>';
table_data += '</tr>';
}
table_data += '</table>';
table_data += '<p><form action="/uploaded" method="post">';
table_data += 'Does the data look OK? If so, click to upload. ';
table_data += '<button class="btn btn-primary" type="submit">Upload</button><p>';
table_data += '<input type="hidden" id="data" name="data" value='+send_data+'>';
table_data += '<input type="hidden" name="class_id" value="{{ class_id }}">';
table_data += '</form>';
table_data += 'Otherwise, fix the file and reload.';
document.getElementById("result_table").innerHTML = table_data;
}
</script>
The JavaScript can be made a lot simpler. If you do the following instead, do you have any problems with the JSON getting cut off?
document.getElementById('update-data-from-file').addEventListener('change', function(evt){
var file = evt.target.files[0];
document.getElementById('filename').innerText = file.name
if (file === "")
return;
Papa.parse(file, {
header: true,
skipEmptyLines: true,
complete: function(results) {
json = results.data
console.log(json)
// Do stuff with the json here
}
});
document.getElementById('update-data-from-file').value = ''
})
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.0.2/papaparse.min.js"></script>
</head>
<body>
<label>
Upload CSV
<input type="file" name="File Upload" id="update-data-from-file" accept=".csv" />
</label>
<div id="filename">No file chosen</div>
</body>
</html>
The problem was the way I was sending the JSON string -- it wasn't in quotes so anytime there was a space in a value, there was a problem.
To fix it: I got the JSON from the answer above, then before sending the JSON string via a POST request, I enclosed it in quotes.
send_data = JSON.stringify(json);
send_data = "'" + send_data + "'";
I am now able to send values that have spaces in it.

sending checkbox array from js to django views

I'm confused about how to do it via Ajax or Json, but how can I send the selection array (curCheck) on-click to Django views and receive it as a python array
javascript
document.getElementById('results').addEventListener('click', function(){
html_table = '<thead><tr><th>Currency</th><th>Amount</th><th>Symbol</th>><tr/><thead/>'
var checkElements = document.getElementsByClassName('ch');
for(var i =0; i< curname.length; i++){
if (checkElements[i].checked) {
var curChecked = curname[i];
var JsonArr = JSON.stringify(curChecked);
postcurChecked(JsonArr)
html_table += '<tr><td>' + curname[i] + '</td>';
}
}
document.getElementById('result_table').innerHTML = html_table;
},false;
ajax
function postsubChecked(curChecked) {
$.ajax({
"url": "http://127.0.0.1:8000/results/",
"type": "POST",
"data": {"checkbox": curChecked},
"headers": { 'X-CSRFToken': getCookie('csrftoken')}
})
}
in django
def currencyChecked(request):
body_unicode = request.body.decode('utf-8')
body_unicode = body_unicode.replace('%22','')
print(body_unicode) json_data = json.loads(body_unicode.read())
I would like to see the python array print to see it is passed to the back
but I keep getting this error:
json_data = json.loads(body_unicode.read()) AttributeError: 'str' object has no attribute 'read'
For getting the selected checkbox values and sending as an array using ajax you can use jquery like this:
consider you have multiple checkboxes and a button.
<input type="checkbox" name="imageName">
<input type="checkbox" name="imageName">
.......
<button id="deletePhoto">Delete</button>
after selecting multiple checkbox values click on this button. On clicking the below jquery will be triggered to make an arrya of selected checkbox values.
//jquery for getting the selelcted checkbox values
$(document).on("click","#deletePhoto",function(){
var favorite = [];//define array
$.each($("input[name='imageName']:checked"), function(){
favorite.push($(this).val());
});
alert("Photo Selected: " + favorite.join(", "));
if(favorite.length == 0){
alert("Select Photo to delete");
return false;
}
//ajax for deleting the multiple selelcted photos
$.ajax({type: "GET",
url: "/olx/deletePhotoFromEdit",
data:{
favorite:favorite
},
success: function(){
// put more stuff here as per your requirement
});
}
});
});
In the view you can get the array like this:
selected_photo = request.GET.getlist('favorite[]')

In AngualrJS using $http, how to get the value of a variable set in Python CGI?

I'm making a POST request from AngularJS to Python.
I started with an JavaScript example. It works properly returning all the values.
However, when I try to do it from AngularJS I'm not able to read the value of the variable posted.
JAVASCRIP EXAMPLE THAT WORKS PROPERLY (I'm able to get the value (Mike) back of Name):
JS code
<script language="Javascript">
function asyncChange()
{
var request;
if (window.XMLHttpRequest) {
request = new window.XMLHttpRequest();
} else {
// Versiones antiguas de Internet Explorer.
request = new window.ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST","nctest.py" , true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("Name=Mike");
request.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("myLabel").innerHTML = "Hello " + request.responseText + "!";
}
}
}
</script>
nctest.py
#!/usr/bin/python
import cgi
input = cgi.FieldStorage()
print "Content-type: text/html\n\n"
print "input[Pe].value: "
print input["Pe"].value
ANGULARJS DOESN'T WORK PROPERLY (I'm not able to get the value (Mike) back of Name):
Angularjs code:
(function(){
'use strict'
var sectest= {
controller:sectestCtrl,
templateUrl:'app/components/component_test/test.html',
}
angular
.module('myapp')
.component('secTest',sectest);
function sectestCtrl($http){
var prac= this;
prac.method = 'POST';
prac.url = 'nctest.py';
prac.data = {Name : 'Mike'};
prac.data_answer
prac.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
prac.sendHTML = send;
function send(){
prac.code = null;
prac.response = null;
$http({method: prac.method, headers: prac.headers, url: prac.url, data: $.param(prac.data)}).
then(function(response) {
prac.status = response.status;
prac.data_answer = response.data;
console.log("OK prac.data_answer: ", prac.data_answer)
}, function(response) {
prac.data_answer = response.data || 'Request failed';
prac.status = response.status;
});
};
}
})();
nctest.py code
#!/usr/bin/python
import json
import cgi
input = cgi.FieldStorage()
print "Content-type: text/html\n\n"
print input["Name"].value
The problem is that prac.data_answer prints blank value.
I have already try with different headers for both angularjs and python codes but none seems to work:
prac.headers = { 'Content-Type': 'application/json' };
prac.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
prac.headers = { 'Content-Type': 'text/html\n\n' };
Many thanks.
There are 2 separate issues you're trying to address. Server (CGI) & client(angularjs). First check to see that you are receiving the data over the network - using Chrome developer tools, under the Network tab. If so, there's no need to change the Content-Type to json, since angular by default assumes all http data is in json format.
I don't think you need all those attributes for a post request. Seems like an overkiller when it can be simpler. Try this:
$http.post(url, data).then(function(response){
console.log(response.data);
});

flask request.args.getlist returns empty list

I am new to web development and trying to solve the following problem. My app has several checkboxes and I need to get values of checked checkboxes. Later, I use those values in further data manipulations and pass the final result using ajax. When I try:
values = request.args.getlist('check')
print values
the list is empty.
values = request.values.getlist('check')
doesn't work ether.
Flask portion:
#app.route('/smiles_to_chemfig')
def smiles_to_chemfig():
smiles_mol = request.args.get("smiles_mol")
values = request.args.getlist('check')
print values
lst = ' '.join(values)
chemfig, pdflink = smiles_mol_to_chemfig(lst,'-i direct', smiles_mol)
return jsonify(outcome = chemfig, pdf_link = pdflink)
ajax:
$(function(){
$("button#smiles").on('click', function(){
if ($('textarea[name=smiles_mol]').val()=="") {
//$("#txt_area").html("PLEASE FILL OUT THIS FIELD !")
alert("PLEASE FILL OUT THIS FIELD !");
}
else {
$.getJSON('/smiles_to_chemfig', {
smiles_mol: $('textarea[name=smiles_mol]').val()
}, function(data) {
$("#txt_area").text(data.outcome);
console.log(data.outcome);
$("#pdf").attr('src', data.pdf_link);
});
}
return false;
});
});
I suspect, that it has something to do with ajax because if I do not implement ajax everything woks good but I need to use ajax. Any suggestions and comments are highly appreciated!

Categories