Loop through MongoDB docs? - javascript

With a basic AJAX web app running locally, a Form POSTs data through Express/Node.js to MongoDB, and a button onClick responds in a rendering of the Mongo document(s) in a div-box.
Using Swig for templating, onClick of the button is only returning a right-brace to appear in the html div-box.
}
How can this be edited to loop through each MongoDB document?
wrapper.html:
{% for go in allDOCs %}
_wrapperGet('{"getting":"{{ keyName }}"}')
{% endfor %}
..where the ajax posts the wrapper data in index.html:
<!-- For the Returned Fields -->
<div id="theResponse">
</div><!-- /.theResponse -->
console.log(returnValue); is listing the mongoDB documents:
{"keyName":"Here's a Value!"}, {"keyName":"Here's another Value!"}
..from app.js
function getAllDOCs(res) {
db.collection('dbCollectionName').find({}, {"_id":0}).toArray(function (err, docs) {
console.log("Got the DOCs: " + docs);
var returnValue = "";
for (var i = 0; i < docs.length; i++)
{
if (returnValue == "")
{
returnValue = returnValue + JSON.stringify(docs[i]);
}
else
{
returnValue = returnValue + ", " + JSON.stringify(docs[i]);
}
console.log(docs[i]);
}
console.log(returnValue);
res.render('wrapper', { allDOCs: returnValue });
});
}
index.html AJAX json parsing:
function handleFINDbuttonResponse(data)
{
// parse the json string
var jsonObject = JSON.parse(data);
$('#theResponse').append( jsonObject.getting );
}

Related

How to Show Table from google speadsheet after login (Google Web App)

Everybody . I'm doing some mini web-app but I'm new in programming
,I followed tutorial from "Learn Google Spreadsheets" on Youtube but get a little bit confuse
My App is very simple
1.User login Page (Check Usercode and Pass from firebase) --- DONE!
2.Get data (get Usercode and find data row from spreadsheet) --- DONE!
3.Pass Object to Table --- Need help
var ss= SpreadsheetApp.openById('1l2Q7C5qBF7EsDInlHi1Bv76jeRJwWjixKteBkc8i3ik');
var PayrollSheet = ss.getSheetByName("ข้อมูลล่าสุด") ;
var Route = {} ;
Route.path = function(route,callback){
Route[route] = callback ;
}
function doGet(e) {
Route.path("Login",LoadLogin) ;
Route.path("Table",LoadTable) ;
if(Route[e.parameters.v]){
return Route[e.parameters.v]() ;
}else {
return render("Login") ;
}
}
function LoadLogin(){
return HtmlService.createTemplateFromFile('Login').evaluate() ;
}
function LoadTable(Usercode){
var TargetRow = GetRow(Usercode) ;
var Data = PayrollSheet.getRange(TargetRow,1,1,18).getValues().flat();
var Round = PayrollSheet.getRange(1,2,1,2).getValues().flat();
return render("Table",{array:Data,round:Round}) ;
}
function render(file,argsObject){
var tmp = HtmlService.createTemplateFromFile(file);
if(argsObject){
var keys = Object.keys(argsObject) ;
keys.forEach(function(key){
tmp[key] = argsObject[key] ;
});
} // END IF
return tmp.evaluate() ;
}
Javascript in html file
<script>
function LoginUser() {
var usercodeIn = document.getElementById("Usercode").value;
var passwordIn = document.getElementById("Password").value;
google.script.run.withSuccessHandler(function(User){
if(User != 'FALSE') // Found User
{
document.getElementById("errorMessage").innerHTML = "welcome " + User ;
google.script.run.LoadTable(usercodeIn) ;
}
else if(User == 'FALSE') //Not Found User
{
document.getElementById("errorMessage").innerHTML = "Wrong Password!";
}
}).checkLogin(usercodeIn,passwordIn);
}
</script>
After Login successful I try to run Loadtable(usercode) to render Table.html with data base on usercode but It only login and show success prompt , but not render Table.html
This is sound pretty easy, but I really don't know what to do ,So please help Thank you
Provided there are no Date objects in argsObject you could simply do tmp.argsObject = argsObject.
Code.gs
function render(file,argsObject){
var tmp = HtmlService.createTemplateFromFile(file);
if(argsObject){
tmp.argsObject = argsObject.
}
return tmp.evaluate() ;
}
Then in your templeted HTML.
<table>
<? for (let i = 0; i < argsObject.array.length; i++) { ?>
<tr><td><?= argsObject.array[i] ?></td></tr>
<? } ?>
</table>
Reference
Templated HTML

How to add csrf token in django with js only without ajax?

I basically want to implement a django view that accepts some json data and then also posts a json data which would be displayed.The confirm group view accepts a list of people via json data , forms a group and then returns the group code back to display.
I was getting the Forbidden(403) CSRF token missing or incorrect Error
I am beginner in django and js so please answer accordingly. Thanking you in advance :)
view.py
import json
def confirm_group(request):
data = json.loads(request.body.decode("utf-8"))
grp = Group()
grp.group_code = group_code_generator()
grp.save()
for i in range(len(data)):
Player = Regplayer.objects.filter(pk=data[i]["pk"])
pl = Enteredplayer()
pl.regplayer = Player
pl.group = grp
pl.save()
return JsonResponse(grp.group_code, safe=False)
script.js
function confirm()
{
var i = 0;
var rows= document.getElementById("group").children;
var num= document.getElementById("group").childElementCount;
if(num==0)
{
}
else
{
// alert("Confirm grouping of "+num+" people?");
for(i=0; i < num; i++)
{
send_name=rows[i].children[0].children[0].innerHTML;
send_gender=rows[i].children[3].children[0].innerHTML;
send_clgname=rows[i].children[1].children[0].innerHTML;
send_sport=rows[i].children[2].children[0].innerHTML;
send_id=rows[i].children[5].innerHTML;
myObj["data"].push({"name":send_name, "gender":send_gender, "college":send_clgname, "sport": send_sport, "pk": send_id});
alert(JSON.stringify(myObj));
}
csrf_token = document.getElementById('csrf_token').innerHTML;
myObj["data"].push({"csrfmiddlewaretoken": csrf_token });
//POST TO BACKEND
// Sending and receiving data in JSON format using POST method
//
var ourRequest = new XMLHttpRequest();
var url = "/confirm_group/";
ourRequest.open("POST", url, true);
ourRequest.setRequestHeader("Content-type", "application/json");
// POST
var data = JSON.stringify(myObj);
ourRequest.send(data);
// Obtain
ourRequest.onreadystatechange = function () {
if (ourRequest.readyState === 4 && ourRequest.status === 200) {
var json = JSON.parse(ourRequest.responseText);
var groupCode = json.groupcode;
//json object received
new_group(groupCode);
}
};
// if success call new_group() else call error_handle()
// new_group();
//error_handle();
//empty json object now
}
}
index.html
<span id="csrf_token" style="display: none;">{{ csrf_token }}</span>
<div class="confirm-modal">
<div class="form">
<p id="modal-text"></p>
<button class="btn1" onclick="confirm()">Confirm</button>
<button class="btn2" onclick="close_modal()">Cancel</button>
</div>
</div>

Using Django and Jquery

In addition to this post https://stackoverflow.com/a/17732956 I want to change the order of a list via drag'n'drop and save it afterwards in django backend.
For test purposes and comprehension I've used following fiddle:
http://jsfiddle.net/LvA2z/#&togetherjs=LvHpjIr7L0
and updated the action of the form with my own action. So, instead of script.php, I used action="{% url 'save_order' %}".
In views my function looks like:
def save_order(request):
if (request.method == 'POST'):
list = request.POST['listCSV']
print(list)
Basically I want to change the order of list elements and save it afterwards with the result that after refreshing the page the saved order is given. However I do not know, how pass vars from jquery to django site. When I change the order, I have the sorted list in 'listCSV'. How do I pass this result to django site to save it in db?
EDIT:
If //$("#listsaveform").submit(); is not commented out and I fire this function referenced with my save_order function, I got this error:
jquery-1.10.2.min.js:6 POST http://localhost:8000/overview/saveOrder/ 405 (Method Not Allowed)
EDIT:
Okay, thanks for the hint. I have never worked with ajax and therefore I'm stucking a bit.
I have my list construct:
{% if habits %}
<ul id="sortable">
{% for habit in habits|dictsort:"priority" %}
<li class="ui-state-default">{{habit.title}}</li>
{% endfor %}
</ul>
{% endif %}
and this list construct is sortable with this lines of code:
$(function() {
$( "#sortable" ).sortable();
});
How does look my form?
Here is my solution based on https://impythonist.wordpress.com/2015/06/16/django-with-ajax-a-modern-client-server-communication-practise/.
In JS
// Sort & save order of habits
$(function () {
$('.sort').sortable({
handle: 'button',
cancel: '',
update: function(event, ui) {
var result = $(this).sortable( "serialize", {key: event.target.id});
// alert(result);
var csrftoken = getCookie('csrftoken');
$.ajax({
url : "/overview/saveOrder/", // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
result : result,
}, // data sent with the post request
// handle a successful response
success : function(json) {
console.log(json); // another sanity check
//On success show the data posted to server as a message
// alert('Your list '+json['result']);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
console.log("FAILURE");
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
});
// var sorted = $( ".selector" ).sortable( "serialize", { key: "sort" } );
// console.log(sorted)
})
//For getting CSRF token
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
and on Django side
def save_habit(request):
print('save_habit')
if (request.method == 'POST'):
if request.is_ajax():
habits = Habit.objects.filter(created_by=request.user.userprofile, is_active=True)
habit_title = request.POST.get('habit_title')
habit_trigger = request.POST.get('habit_trigger')
habit_routine = request.POST.get('habit_routine')
habit_targetbehavior = request.POST.get('habit_targetbehavior')
habit_image = request.POST.get('habit_image')
print(habit_image)
image = habit_image.split('http://localhost:8000/media')
print(image[1])
# TODO: was, wenn routine noch gar nicht existiert? --> speichern
obj_routine = Existingroutine.objects.get(name=habit_routine)
obj_targetbehavior = Targetbehavior.objects.get(name=habit_targetbehavior)
for habit in habits:
habit.priority += 1;
# habit.save();
habit = Habit(created_by=request.user.userprofile, is_active=True,
title=habit_title, trigger=habit_trigger, existingroutine=obj_routine,
targetbehavior=obj_targetbehavior, image=image[1])
#habit.save()
data = {"habit_title":habit_title,
"habit_trigger":habit_trigger,
"habit_routine":habit_routine,
"habit_targetbehavior":habit_targetbehavior };
return JsonResponse(data)
return redirect('display_habits')

Update part of a page in jade?

I'm trying to make a search and send back the result to the same site, I've got the search to work but I can't get the result to be sent back. I want the start site to render the information without page reload.
How can I send the search result back to the index.jade page without having to update it?
function pagelist(items, res) {
var document='';
var db = db_login;
if ( items != null){
items.forEach(function(item) {
document += '<a href=share/'+item._id+' class="searchElement">'
document += item.document
document += '</div>'
})
if(document != ''){
res.send(document);
}else{
}
}
}
index.jade
extends layout
block content
block child
child.jade
extends index
block child
!{document}
You can do it the following way:
First, you could update your index.jade like this:
extends layout
block content
#content
block child
And then, there should be some sort of function you call to get your results. I'll call it getResults.
In the callback of that function you can now do the following:
getResults(function(results){
document.getElementById("content").innerHTML = results;
});
I hope that helps.
UPDATE
I'll give you a complete example:
server.js
var express = require("express");
var i = 0;
function getResults(cb){
cb("<div>Result "+(i++)+"</div><div>Result "+(i++)+"</div><div>Result "+(i++)+"</div>");
}
var app = express();
app.set("view engine","jade");
app.get("/",function(req,res){
getResults(function(results){
res.render("page",{results:results});
});
});
app.get("/results",function(req,res){
getResults(function(results){
res.writeHead(200,"OK",{"Content-Type":"text/html"});
res.end(results);
});
});
app.listen(80);
views/page.jade
doctype html
html
head
script.
function update(){
var req = new XMLHttpRequest();
req.open("GET","/results");
req.onreadystatechange = function(){
if(req.readyState == 4){
document.getElementById("content").innerHTML = req.responseText;
}
}
req.send();
}
body
#content!= results
input(type="button",value="Update",onclick="update()")
Run it with node server.js and visit localhost. You should learn from it how it's done ;)

xpages JSON-RPC Service handling response from callback funciton

I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!

Categories

Resources