how a javascript scope can be duplicated? by using for loop? - javascript

I just had this javascript comet call working properly, but found out i need 30 pieces to do the same function but with different value output. check out my code
<script type="text/javascript">
var Comet = Class.create();
Comet.prototype = {
timestamp: 0,
url: 'backend.php',
noerror: true,
pointname: 'GrossElectricityGeneration',
initialize: function() { },
connect: function()
{
this.ajax = new Ajax.Request(this.url, {
method: 'get',
parameters: { 'timestamp' : this.timestamp, 'pointname': this.pointname},
onSuccess: function(transport) {
// handle the server response
var response = transport.responseText.evalJSON();
this.comett.timestamp = response['timestamp'];
this.comett.handleResponse(response);
this.comett.noerror = true;
},
onComplete: function(transport) {
// send a new ajax request when this request is finished
if (!this.comett.noerror)
// if a connection problem occurs, try to reconnect each 5 seconds
setTimeout(function(){ comett.connect() }, 5000);
else
this.comett.connect();
this.comett.noerror = false;
}
});
this.ajax.comett = this;
},
disconnect: function()
{
},
handleResponse: function(response)
{
$('page1b').innerHTML = '<div>' + response['msg'] +'</div>';
$('page1c').innerHTML = '<div>' + '67'+'</div>';
},
}
var comett = new Comet();
comett.connect();
</script>
to do this, a silly way is to copy 30 pieces of ... and rename
comett to 30 different name
30 different #('page1a')#('page1b')
and point name
is there any other way that i can use for loop to duplicate 30 copies with differnet variables ?
thanks....

Related

chrome.storage.local.get not working

Here i'm using to store the multiple value[below is the code]
Here DocName is the Name of the PDF and Base64File is the base64 string of the pdf
var obj = { DocName: res.Value.DocumentName, Base64File: res.Value.Base64File };
chrome.storage.local.set({ 'MyFile': obj });
In next page i'm retriving like this
$(document).on('click', '.sendToPdf', function(){
chrome.storage.local.get('MyFile', function (result) {
var PdfBase64 = result.MyFile.Base64File;
var DocumentName = result.MyFile.DocName;
var arr=new Array();
var item={"CategoryID": 11,"DocumentNumber": "22022018053567","Base64FileData": PdfBase64,"DocumentName": DocumentName,
"OptionalParam1": "sample string 5"};
arr.push(item);
$.ajax({
type: "POST",
url: Documentupload,
headers: {
'Authorization': headerdata,
'Content-Type':'application/json'
},
data:JSON.stringify(arr),
dataType: 'json',
success: function (res) {
if (res.IsSuccess) {
setTimeout(function () {
$("#divLoading").hide();
}, 2000);
//$("#divLoading").hide();
$(".modal-iframe1").attr("src", window.emSigner.OnlineSignUrl + res.Response[0].DocumentID + "&AuthToken=" + AuthToken);
//window.location.reload();
}else{
alert(res.Messages);
window.location.href='/PdfLogin.html';
}
},
error: function (error) {
//alert("Error while communicating to the server");
alert(error.responseText);
window.location.href='/PdfLogin.html';
}
});
});
});
[check this image .sendToPdf(button)]
Question is, if i click the button first time on any icon, the values are retriving correctly, but in second time if i click other than 1st icon i'm getting the values as the before one? it is accepting the previous values only?
How to resolve this,
Help me to come out of this problem.

Save variable from console output Javascript/Python/Jinja2

I am using Trello API to create a card. This works fine but while the script runs it prints a ID variable of the newly created card to the console. I'd like to take this variable and pass it back to my python code. Is this possible? I am using Jinja2 to pass variables from Python to HTML, can I use this here?
This is the output to the console in Chrome, I want to grab the first ID variable so I can work with it in my Python code.
{
"id": "5a46fa28620367df83fe08f7",
"badges": {
"votes": 0,
"attachmentsByType": {
"trello": {
"board": 0,
"card": 0
}
},
"viewingMemberVoted": false,
"subscribed": false,
"fogbugz": "",
"checkItems": 0,
"checkItemsChecked": 0,
Here is my Javascript:
var authenticationSuccess = function() {
console.log('Successful authentication');
};
var authenticationFailure = function() {
console.log('Failed authentication');
};
window.Trello.authorize({
type: 'popup',
name: 'Work Requests App',
scope: {
read: 'true',
write: 'true' },
expiration: 'never',
success: authenticationSuccess,
error: authenticationFailure
});
//console.log(trelloTitle);
//console.log(trelloContent);
var myList = '5a3ec86f7920a6e66b28e4bc';
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
};
//var data = $('#resultsdata').data();
//console.log(trelloId);
var newCard = {
name: trelloTitle,
desc: trelloContent,
// Place this card at the top of our list
idList: myList,
idMembers: trelloId,
pos: 'top'
};
window.Trello.post('/cards/', newCard, creationSuccess);
EDIT: I am now using this AJAX method:
var creationSuccess = function (data) {
console.log('Card created successfully.');
console.log(JSON.stringify(data, null, 2));
var url = "/ajaxtest";
$.post(url, {card_id: data.id});
};
I am having difficulty passing card_id into my python method:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = card_id
I know this is wrong, can anyone help?
Here's the complete answer:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var http = new XMLHttpRequest();
var url = "URL to your server (where you want to send the data)";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send("card_id=" + data.id);
};
This will send the card id as card_id to your server (to the URL you specified) through an AJAX call.
This is assuming that you're only using pure Javascript. If you're using jQuery, then making an AJAX call would be much easier. like:
var creationSuccess = function (data) {
console.log('Card created successfully.');
var url = "URL to your server";
$.post(url, {card_id: data.id});
};
Edit: As for the server code, you could now receive card_id like this:
class AjaxTest(webapp2.RequestHandler):
def post(self):
data = self.request.get('card_id')
Hope that helps.

Reusing a JavaScript AJAX call before another AJAX call

I have two buttons that both performs AJAX call:
$("#save").click(function() {
$.ajax({
type: "POST",
url: saveEntryURL,
data: { id: $("#id").val() },
success: function(r) {
...
},
error: function(r) {
...
}
})
})
$("#tag-as-final").click(function() {
$.ajax({
type: "POST",
url: finalizeEntryURL,
data: { id: $("#id").val() },
success: function(r) {
...
},
error: function(r) {
...
}
})
})
The requirement is that when the user click the finalize button, the system will first perform a save before actually tagging it as final. To reuse the code attached to the save button, I call the onclick listener of the save button before the actual AJAX call like this:
$("#tag-as-final").click(function() {
$("#save").click()
^^^^^^^^^^^^^^^^^^
$.ajax({
type: "POST",
url: finalizeEntryURL,
But it will not do "save-and-finalize-after" behavior since both AJAX calls are asynchronous. I need to run one after another, but cannot afford to make the AJAX call of the save button synchronous (I'm doing also a lot of other things while the tagging occurs occurs). I know this would be silly but I'm thinking something similar to...
$("#tag-as-final").click(function() {
$("#save").click().peformAsyc()
^^^^^^^^^^^^
$.ajax({
type: "POST",
url: finalizeEntryURL,
...that will force it to finish performing first the chained function before continuing, but I know that is not available. Is there any way to do this? My current work-around is placing the same save AJAX function inside the finalize AJAX function, though it doesn't allow me to code DRY (Don't Repeat Yourself):
$("#tag-as-final").click(function() {
$.ajax({
type: "POST",
url: saveEntryURL,
data: { id: $("#id").val() },
success: function(r) {
...
$.ajax({
type: "POST",
url: finalizeEntryURL,
data: { id: $("#id").val() },
success: function(r) {
...
},
error: function(r) {
...
}
})
},
error: function(r) {
...
}
})
})
It's pretty simple, you are better using jquery "promises". Like so:
var generalSettings = { }; //Settings for AJAX call.
var jqXHR = $.ajax(generalSettings); //Do AJAX call.
generalSettings.data = 'newdata'; //update generalSettings
jqXHR.done(function(data){
$.ajax(generalSettings); //New Petition with updated settings.
});
This is using ES6 promises and jQuery promises:
function doAjaxAsPromise(settings){
return new Promise(function(resolve){
var jqXHR = $.ajax(settings);
jqXHR.done(function(data){
resolve(data);
});
});
}
var settings = { };
var petition = doAjaxAsPromise(settings);
var secondpetition = petition.then(function(data){
//work with data
//new settings
var settings = { };
return doAjaxAsPromise(settings);
});
var thirdpetition = secondpetition.then(function(data){
//work with data
//new settings
var settings = { };
return doAjaxAsPromise(settings);
});
//If needed to reuse settings object outside promise scope:
//var settings = Object.create(settings);
Some other nice thing you can do for code reuse:
function save(settings) {
var prom = doAjaxAsPromise(settings);
return prom.then(function(data){
//do something with your data.
});
}
function tagAsFinal(savedPromise, settings){
return savedPromised.then(function(){
var prom = doAjaxAsPromise(settings);
return prom.then(function(data){
//work with data;
});
});
}
$('save').on('click', function(){
save(settings); //settings = $.ajax settings.
});
$('tagAsFinal').on('click', function(){
var generalSettings = { };
var settingsone = Object.create(generalSettings);
var settingstwo = Object.create(generalSettings);
var saved = save(settingsone); //$.ajax settings.
tagAsFinal(saved, settingstwo);
});
//Can still be reduced.

Multiple ajax calls when previous one completes

I have these ajax calls that need to get called when the previous one is success, meaning once the first ajax is OK, call the 2nd ajax, once the 2nd ajax is OK call the 3rd one, etc so on. I started with a few ajax calls so it was fine to chain them up like this below but now I have about 20 of them and it'd be a mess to chain them up like this.
$.ajax({
url: 'urlThatWorks1',
success: function (data) {
//call someMethod1 with data;
$.ajax({
url: 'urlThatWorks2',
success: function (data) {
//call method2 with data;
//another ajax call ... so on
}
}.... 19 level deep
So I need to make it bit easier to read and maintain so I'm thinking something like
var ajaxArray = [];
var function1 = $.ajax('urlThatWorks1', data I get back from the 'urlThatWorks1' call);
myArray.push(function1);
var function2 = $.ajax('urlThatWorks2', data I get back from the 'urlThatWorks2' call);
myArray.push(function2);
//etc 19 others
myArray.each(index, func){
//Something like $.when(myArray[index].call()).done(... now what?
}
Hope this makes sense, I'm looking for a way of ajax call array from which I can call an ajax call on whose success I call the next ajax in the array. Thanks.
Create a recursive function to be called in sequence as the ajax requests return data.
var urls = [ "url.1", "url.2", ... ];
var funcs = [];
function BeginAjaxCalls()
{
RecursiveAjaxCall(0, {});
}
function RecursiveAjaxCall(url_index)
{
if (url_index >= urls.length)
return;
$.ajax(
{
url: urls[url_index],
success: function(data)
{
funcs[url_index](data);
// or funcs[urls[url_index]](data);
RecursiveAjaxCall(url_index + 1);
}
});
}
funcs[0] = function(data)
// or funcs["url.1"] = function(data)
{
// Do something with data
}
funcs[1] = function(data)
// or funcs["url.2"] = function(data)
{
// Do something else with data
}
Try
$(function () {
// requests settings , `url` , `data` (if any)
var _requests = [{
"url": "/echo/json/",
"data": JSON.stringify([1])
}, {
"url": "/echo/json/",
"data": JSON.stringify([2])
}, {
"url": "/echo/json/",
"data": JSON.stringify([3])
}];
// collect responses
var responses = [];
// requests object ,
// `deferred` object , `queue` object
var requests = new $.Deferred() || $(requests);
// do stuff when all requests "done" , completed
requests.done(function (data) {
console.log(data);
alert(data.length + " requests completed");
$.each(data, function (k, v) {
$("#results").append(v + "\n")
})
});
// make request
var request = function (url, data) {
return $.post(url, {
json: data
}, "json")
};
// handle responses
var response = function (data, textStatus, jqxhr) {
// if request `textStatus` === `success` ,
// do stuff
if (textStatus === "success") {
// do stuff
// at each completed request , response
console.log(data, textStatus);
responses.push([textStatus, data, $.now()]);
// if more requests in queue , dequeue requests
if ($.queue(requests, "ajax").length) {
$.dequeue(requests, "ajax")
} else {
// if no requests in queue , resolve responses array
requests.resolve(responses)
}
};
};
// create queue of request functions
$.each(_requests, function (k, v) {
$.queue(requests, "ajax", function () {
return request(v.url, v.data)
.then(response /* , error */ )
})
})
$.dequeue(requests, "ajax")
});
jsfiddle http://jsfiddle.net/guest271314/6knraLyn/
See jQuery.queue() , jQuery.dequeue()
How about using the Deferred approach. Something like:
var arrayOfAjaxCalls = [ { url: 'https://api.github.com/', success: function() { $("#results").append("<p>1 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>2 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>3 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>4 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>5 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>6 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>7 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>8 done</p>"); } },
{ url: 'https://api.github.com/', success: function() { $("#results").append("<p>9 done</p>"); } }
];
loopThrough = $.Deferred().resolve();
$.each(arrayOfAjaxCalls, function(i, ajaxParameters) {
loopThrough = loopThrough.then(function() {
return $.ajax(ajaxParameters);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="results"></div>
You could use the async library, which has a bunch of functions like waterfall or series which could solve your problem.
https://github.com/caolan/async#series
https://github.com/caolan/async#waterfall

Ext.Ajax.isLoading return false when not all requests were completed

I need to do some action on panel after all Ajax requests completed and for this purpose I added handler:
Ext.Ajax.on('requestcomplete', function(conn, response, options) {
if (!Ext.Ajax.isLoading()) {
// do action
}
});
But I found that in case when execute request by Ext.Ajax.request method Ext.Ajax.isLoading() return false regardless in which state this request.
UPDATE
Ext.Ajax.request({
url: 'someUrl',
timeout: 50000,
scope: this,
success: function(response, options) {
//some action
},
params: {
//some params
},
callback: function() {
//some action
}
});
Do someone know how to fix it? Or possible exist some other way for define that all requests completed?
Unfortunately the isLoading() function only tells you if the request is still waiting for an answer. So false means that it hasn't started yet or it is finished.
If you know how many requests you're going to send in your panel, you could make a workaround using the native setInterval() function.
it could look like this:
var itemsLoaded = 0,
loadFailed = false,
pID;
for(var i = 0; i < amount; i++) {
Ext.Ajax.request({
url: 'someUrl',
timeout: 50000,
scope: this,
success: function(response, options) {
itemsLoaded++;
//other actions
},
failure: function() {
loadFailed = true;
},
params: {
//some params
},
callback: function() {
//some action
}
});
}
pID = setInterVal(function() {
if(itemsLoaded == amount) {
clearInterval(pID);
//place here the actions you want to do when all items are loaded
} else if(loadFailed) {
clearInterval(pID);
}
}, 100); //milliseconds you want to retry the check

Categories