how to send ids of object to backend funtion? - javascript

My knowledge of front end it is not so good, and I don't know how to send array of ids to back end which will get all data and will be open it into new page. pls help
there my function:
#has_session_params('tin')
def print_documents(request):
doc_ids = request.POST.getlist('doc_ids[]')
tin = request.session['tin']
params = dict()
template = 'documents/documents_to_print.html'
params['Docs'] = docs
params['pb'] = pb
params['is_pdf'] = request.GET.get('is_pdf', 'false')
params['host'] = request.scheme + "://" + request.META["HTTP_HOST"]
params['url'] = settings.SITE_URL + request.get_full_path()
params['doc_type'] = INVOICE_TYPE
invoice_list = list()
for doc_id in doc_ids:
response = proxy.get_invoice_by_id(invoice_id=doc_id, tin=tin)
if response.status.code != pb.ResponseStatus.OK:
response = proxy.get_invoice_draft_by_id(
invoice_draft_id=doc_id, tin=tin)
invoice_list.append(response.invoice)
params['invoices'] = invoice_list
return render(request, template, params)
I know how to get one object by id, it will be like:
def print_document(request, doc_id):
and something like that, and where url for function will be look like that:
url(r'^print_documents/(?P<doc_id>[a-z\d]{24})/$', invoices.print_documents, name='print_documents')
and new page link will be like that localhost:8000/documents/print_documents/{doc_id}
and this method I can just call like :
print
but now I want to select several documents and send doc_ids, and I know that I can to like method above but I don't want big link. And how I can send array of ids to back end correctly?
now I have something like that:
printAll.on("click", function(){
var invoicesID = [];
$('input.select-inv-check:checked').each(function() {
invoicesID.push($(this).data('docid'));
});
var url = Globals.printAll;
$.post( url, { doc_ids: invoicesID } ).done(function(result) {
console.log("result", result[0].Docs);
if(result.code == 0){
}else{
alert(result.message);
}
});
});
And I know that it doesn't correct! pls help

Related

How do I trim/strip URL down to get specific data?

How would I go about trimming/stripping the URL down to get specific data...
So: https://www.example.com/items/423455344/size-39
Would become: 423455344
Any ideas?
If you know the URL is always going to match that format, you could do something like this.
function getData() {
let foo = window.location.href.split("/"); //this gives you an array with the data between the slashes
let searchController = "items"; //this is the key before the data you need
for (let i=0; i<foo.length; i++){
if (foo[i] === searchController){
searchController = "/true/";
} else if (searchController === "/true/") {
return foo[i];
}
}
}
Let me know if you have any questions

How do I access a data nested in JSON in javascript?

I have been trying to figure this out for hours. I've seen this SO question and I still cannot figure this out.
I have some Jason data that I know begins like this:
{
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
....
I've written the following to get at the information like "poolIndex" and "stakingStrategy":
function parseTheDataFunctionSushi(walletAddress, networkName){
// calls a funciton to pull and parse the api data
var walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
var networkName = "polygon";
var theparsedJSONdata = pullAndParseAPISushi(walletAddress, networkName)
console.log("object keys are " + Object.keys(walletAddress));
var firstCrack = theparsedJSONdata[walletAddress][0]['poolIndex']
console.log("firstCrack is " + firstCrack)
This does not work. I've written firstCrack every way I can think of
theparsedJSONdata[walletAddress].poolIndex
theparsedJSONdata[walletAddress][0].poolIndex
None of them work. So frustrating. Any help would be appreciated.
For what it's worth, `Object.keys(walletAddress) returns
object keys are 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41
Here's the other function:
function pullAndParseAPISushi (walletAddress, networkName){
console.log("walletAddress inside pullAndParseAPISushi is = " + walletAddress);
console.log("network is " + networkName);
var apiKEY = "96e0cc51-a62e-42ca-acee-910ea7d2a241"; // API key from Zapper
var url = "https://api.zapper.fi/v1/staked-balance/masterchef?addresses%5B%5D="+ walletAddress + "&network=" + networkName + "&api_key=" + apiKEY;
// assembles the API URL with the wallet addressa, network and name
console.log("url is " + URL);
var response = UrlFetchApp.fetch(url); // pulls data from the API
console.log(response)
var theparsedJSONdata = JSON.parse(response); // parses the JSON response from the API
console.log(theparsedJSONdata)
return theparsedJSONdata
}
If the data structure is indeed as you specified, then one of the attempts you tried should work. See below for a functional example.
const data = {
"0x123454843eacf5c5318e1234504251b937d12345": [
{
"poolIndex": 0,
"stakingStrategy": "masterchef",
"farmName": "sushiChef",
}
]
}
const walletAddress = "0x123454843eacf5c5318e1234504251b937d12345";
console.log(data[walletAddress][0].poolIndex);
console.log(data[walletAddress][0].stakingStrategy);
Have you tried?
theparsedJSONdata.walletAddress[0].poolIndex
don't have enough rep to make a comment but I think this might work, let me know!

Pass parameter in bbUI to another page failed

Based On : Blackberry Wiki Screen
With my full code : My Full Code
If i user onscreenready function to PASS MY PARAMETER from page A like this :
ondomready: function(element, id) {
if (id == 'UPDATE') {
UPDATE_initialLoad(element, params);
}
}
For pages that I would give / throw parameters (Let's just say page B), how do I win or get results / parameters provided by the previous form. I want to make a form update the data in the form, and will be filled all the time throwing fieldnya parameter data.
Im using like this in my Page B :
function UPDATE_initialLoad(element, params) {
setTimeout(UPDATE_loadAfterTimeout,100);
}
function UPDATE_loadAfterTimeout() {
var id = data_id
var nmDepan = data_depan
var nmBelakang = data_belakang
var phone = data_phone
var email = data_email
document.getElementById('txtID').value = id
document.getElementById('txtNMDEPAN').value = nmDepan
document.getElementById('txtNMBELAKANG').value = nmBelakang
document.getElementById('txtPhone').value = phone
document.getElementById('txtEmail').value = email
}
But result is failed...
Please help me
You'll want to push data to the page:
bb.pushScreen("myPage.html", "UPDATE", myParams);
Then this will fire when the page is loaded:
ondomready: function(element, id, params) {
if (id == 'UPDATE') {
UPDATE_initialLoad(element, params);
}
}
Make sure to pass the parameters to your delayed function:
function UPDATE_initialLoad(element, params) {
setTimeout(UPDATE_loadAfterTimeout(params),100);
}
function UPDATE_loadAfterTimeout(params) {
var id = params['data_id'];
var nmDepan = params['data_depan'];
var nmBelakang = params['data_belakang'];
var phone = params['data_phone'];
var email = params['data_email'];
document.getElementById('txtID').value = id
document.getElementById('txtNMDEPAN').value = nmDepan
document.getElementById('txtNMBELAKANG').value = nmBelakang
document.getElementById('txtPhone').value = phone
document.getElementById('txtEmail').value = email
}
I hope this helps.

JavaScript control flow in node/redis: returning from inside callback?

Newbie question. Why is this JavaScript function returning undefined?
var redis = require("redis"), client = redis.createClient();
function generatePageUrl() {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
client.smembers("url:" + randomStr, function (err, data ) {
if (data.length != 0) {
// URL already in use, try again
return getPageUrl();
}
return randomStr;
});
}
var page_url = generatePageUrl();
// add it to the database, etc
I guess it must be getting to the end and returning before it reaches the inside of client.smembers.
But I really need to check the contents of the Redis set before it returns: can I get it to return from inside the callback? If not, what can I do?
Also, advice on the way I've used this function recursively would be welcome - I'm not sure it's completely sensible :)
Thanks for helping out a newcomer.
You can't return from inside a callback. Do it like this:
var redis = require("redis"), client = redis.createClient();
function generatePageUrl(cb) {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
client.smembers("url:" + randomStr, function (err, data ) {
if (data.length != 0) {
// URL already in use, try again
getPageUrl(cb);
}
cb(randomStr);
});
}
generatePageUrl(function(page_url){
// add it to the database, etc
});
If you don't like this style, you might want to consider streamlinejs - it makes you able to write your code like this:
var redis = require("redis"), client = redis.createClient();
function generatePageUrl(_) {
var randomStr = randomInt.toString(32);
// Check whether this URL is already in our database;
var data = client.smembers("url:" + randomStr, _);
if (data.length != 0) {
// URL already in use, try again
return getPageUrl(_);
}
return randomStr;
}
var page_url = generatePageUrl(_);
// add it to the database, etc

$.getJSON only returns partial and an empty array

I am creating an object to handle the YouTube API and I have two methods:
getCommentList - getting a url for the current upload,for example http://gdata.youtube.com/feeds/api/videos/VIDEO_ID/comments?alt=json and return an array of objects - author of the comment and the content of the comment.
getEntriesObject - returning an array with objects for each upload entry we have title,thumbnail,and the comment list that returned from getCommentList
My jQuery code:
var Youtube = {
getCommentObject : function(url){
if( url ){
var currentCommentFeed = {},
commentsList = [];
$.getJSON(url,function(data){
$.each(data.feed.entry,function(index){
currentCommentFeed = this;
commentsList.push({
author : currentCommentFeed.author[0].name.$t,
content : currentCommentFeed.content.$t
});
});
return commentsList;
});
}
},
getEntriesObject : function(){
var username = 'SOMEYOUTUBEUSERHERE',
url = 'http://gdata.youtube.com/feeds/api/users/' + username + '/uploads?alt=json',
currentEntry = {},
currentObject = {},
entryList = [];
// Scope fix
var that = this;
$.getJSON(url,function(data){
$.each(data.feed.entry, function(index){
// Caching our entry
currentEntry = this;
// Adding our entry title and thumbnail
currentObject = {
title: currentEntry.title.$t
};
if(currentEntry.media$group.media$thumbnail.length == 4)
currentObject['thumbnail'] = currentEntry.media$group.media$thumbnail[3].url;
// Let`s get the comments - undefined....
currentObject['comments'] = that.getCommentObject(currentEntry.gd$comments.gd$feedLink.href + "?alt=json");
console.log(currentObject);
entryList.push(currentObject);
});
});
return entryList;
}
/*
entry[i].title.$t
entry[i].gd$comments.gd$feedLink.href + "?alt=json"
entry[i].media$group.media$thumbnail[3]
// Comments
entry[i].author.name.$t
entry[i].author.content.$t
*/
};
I have console.log(currentObject) and am getting the title. But am not getting the thumbnail URL and the comments.
In addition, when I run getEntriesObject I get back an empty array.
When you call return in the callback to $.getJSON you are returning only that callback function, not the "outer" getCommentObject. Thus when you later call that.getCommentObject you're not getting anything in return (undefined).
getCommentObject: function(url){
if( url ){
// Snip ...
$.getJSON(url,function(data){
// Snip ...
return commentsList; // <- Here
});
}
}
To amend this make getCommentObject take a callback function.
getCommentObject: function(url, callback){
if( url ){
// Snip ...
$.getJSON(url,function(data){
// Snip
// Remove the return statement
callback(commentsList);
});
}
}
Call this function like this:
that.getCommentObject(
currentEntry.gd$comments.gd$feedLink.href + "?alt=json",
function (commentsList) {
currentObject['comments'] = commentsList;
});
Replacing
currentObject['comments'] = that.getCommentObject(currentEntry.gd$comments.gd$feedLink.href + "?alt=json");
You are getting the empty comments because the return statement is in the wrong place. It is in the getJSON callback function. You need to move it from line no 19 to 21 so that it becomes the return statement for getCommentObject. This will fix the first problem. (comments undefined)
Second getEntriesObject is empty because, for some users youtube is returning "Service Unavailable" error for the json request. This happened for when I tried with some random username on youtube.
I checked your program with youtube username "google". After changing the return statement it worked fine.
Hope this helps.

Categories