I got the following script to loop through a page's options to fetch subsequent values:
var casper = require('casper').create();
casper.on('remote.message', function (message) {
this.echo(message);
});
casper.on( 'page.error', function (msg, trace) {
this.echo( 'Error: ' + msg, 'ERROR' );
});
casper.start(url, function() {
this.evaluate(function() {
// nothing
});
this.then(function() {
ddlArea_options = this.getElementsAttribute('#ddlArea option', 'value');
for(var i = 0; i < ddlArea_options.length; i++) {
if(ddlArea_options[i] != '') {
this.echo(ddlArea_options[i]);
startQuery('myID', ddlArea_options[i]);
}
}
});
});
where startQuery(id, val) is a function contains casper.start():
function startQuery(id, val) {
casper.start(url, function() {
this.echo('startQuery started');
var obj = {};
obj['#' + id] = val;
this.fillSelectors('#form1', obj, true);
this.evaluate(function() {
__doPostBack('ddlArea', '');
});
this.then(function() {
this.echo("doPostback complete");
var values = this.getElementsAttribute('#anotherSelect option', 'value');
for(var i = 0; i < values.length; i++) {
this.echo(values[i]);
}
});
});
casper.run();
}
but startQuery() is executed once only, on the last item in for-loop. What did I miss?
You can only have one start-run pair per casper instance. start resets all the steps before, so everything that was in the queue is gone. In startQuery, you can change casper.start to casper.thenOpen and remove casper.run completely.
Related
Simply i just loop an array, and submit data with get in the loops, but i runs so fast that the server stops running. I mini Ddos myself doing this. How i can i make the loop wait until the calls finish, perhaps adding a 1 sek break between loops
$( document ).on("submit", "#add_links", function() {
var error = 0;
var success = 0;
var total = 0;
//Gets data from input field
var new_urls = $("#new_urls").val();
var array_urls = new_urls.split("\n");
var promiss = [];
array_urls.forEach(function(entry) {
var request = $.get("action.php",
{
add_link: "1",
url: encodeURIComponent(entry.trim()),
},
function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
if (data == 1)
{
success++;
total++;
//update fields removed in this post
$("#success_count").html((success));
$("#total_count").html((total));
}
if (data == 2) {
error++;
total++;
//update fields removed in this post
$("#error_count").html((error));
$("#total_count").html((total));
}
});
promiss.push(request);
});
$.when.apply(null, promiss).done(function(){
//do something when done;
});
return false;
});
You could use recursive function to achieve this.
Example
$(document).on("submit", "#add_links", function() {
var error = 0;
var success = 0;
var total = 0;
var new_urls = $("#new_urls").val();
var array_urls = new_urls.split("\n");
var promiss = [];
let index = 0;
function sendAjaxCall() {
if(count >= array_urls.length) return;
var request = $.get(
"action.php",
{
add_link: "1",
url: encodeURIComponent(array_urls[index].trim())
},
function(data, status) {
console.log("Data: " + data + "\nStatus: " + status);
if (data == 1) {
success++;
total++;
$("#success_count").html(success);
$("#total_count").html(total);
}
if (data == 2) {
error++;
total++;
$("#error_count").html(error);
$("#total_count").html(total);
}
count++;
promiss.push(request);
sendAjaxCall();
}
);
}
$.when.apply(null, promiss).done(function() {
$("#close_bug_reportwindow").html(
"Import done, close tab by clicking here"
);
$("#close_icon").html('(<i class="fas fa-times"></i>)');
$("#progress").remove();
});
return false;
});
it doesn't pass any thing
and if i send index on for loop it send all the last index of cell
I want distinguish between element has the same class
I want alternative for use 'unsafe-inline' and send parameter via html
$(document).on('deviceready', function () {
console.log("Device is ready!");
//myApp.alert("aa","aa");
var cell = document.querySelectorAll('.item-title');
for (var i = 0; i < cell.length; i++) {
cell[i].addEventListener("click", function() {
aaa(cell[i].dataset.index);
}, true);
//myApp.alert("aa"+, "aa");
// x[i]=i;
}
});
function aaa(id) {
myApp.alert(id);
}
$(document).on('deviceready', function () {
console.log("Device is ready!");
//myApp.alert("aa","aa");
var cell = document.querySelectorAll('.item-title');
for (var i = 0; i < cell.length; i++) {
cell[i].addEventListener("click", function( event ) {
const id = event.target.dataset.id;
aaa(id);
}, true);
//myApp.alert("aa"+, "aa");
// x[i]=i;
}
});
function aaa(id) {
myApp.alert(id);
}
I am trying to create a stop button in my webapp. The webapp creates bulk shortcuts to different files. I have tried using $.connection.shortcutHub.stop() however this comes up with an error saying Cannot read property 'shortcutHub' of undefined(anonymous function)
The code is below. I need the connection to be stopped once the stop button has been clicked. The stop button's id is stopButton.
$(document).ready(function () {
// initialize the connection to the server
var progressNotifier = $.connection.shortcutHub;
// client-side sendMessage function that will be called from the server-side
progressNotifier.client.sendMessage = function (message, percent) {
// update progress
UpdateMessage(message, percent);
};
progressNotifier.client.redo = function () {
redo();
};
progressNotifier.client.success = function () {
success();
};
progressNotifier.client.fail = function () {
fail();
};
// establish the connection to the server and start server-side operation
$.connection.hub.start().done(function () {
$('#confirmbutton').click(function () {
jQuery.noConflict();
document.getElementById('closeButton').setAttribute("class", "btn btn-default hidden");
$('#myModal').modal('show');
//document.getElementById('confirmbutton').disabled = true;
//document.getElementById('barcodepanel').setAttribute("class", "panel panel-default");
var ticket = getCookie('ticket');
var path = getCookie('CBSShortcut_Path');
var checkeddocs = getCheckedBoxes("dcheck");
var checkedfolders = getCheckedBoxes("fcheck");
progressNotifier.server.createshortcuts(ticket, path, checkeddocs, checkedfolders);
});
$('#stopButton').click(function () {
document.getElementById('closeButton').setAttribute("class", "btn btn-default");
document.getElementById('confirmbutton').disabled = false;
//What do I put here?
});
});
function UpdateMessage(message, percent) {
// get result div
var msg = $("#result");
// set message
msg.html(message);
//set value of progress bar
document.getElementById('closeButton').setAttribute("class", "btn btn-default hidden")
$('#progressbar').css('width', percent + '%').attr('aria-valuenow', percent);
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function redo() {
document.getElementById('confirmbutton').disabled = false;
jQuery.noConflict();
$('#myModal').modal('hide');
}
// Pass the checkbox name to the function
function getCheckedBoxes(chkboxclass) {
var checkboxes = document.getElementsByClassName(chkboxclass);
var checkboxesChecked = [];
var ids = "";
// loop over them all
for (var i = 0; i < checkboxes.length; i++) {
// And stick the checked ones onto an array...
if (checkboxes[i].checked) {
checkboxesChecked.push(checkboxes[i]);
ids = ids + checkboxes[i].getAttribute("Name") + ",";
}
}
// Return the array if it is non-empty, or null
//return checkboxesChecked.length > 0 ? checkboxesChecked : null;
return ids;
}
}
);`
Any help is appreciated. I have tried everything that google has thrown my way (which has been mostly stackoverflow sites) and I am still having the same problem.
Have you tried:
$.connection.hub.stop().done(function() {
alert('stopped');
});
it will work.
You want to use the global SignalR Hub client connection because hubs share a single connection (aka don't use progressNotifier to do anything with the connection, only to listen for and send events.)
Your code to test this could look like:
$('#stopButton').click(function () {
document.getElementById('closeButton').setAttribute("class", "btn btn-default");
document.getElementById('confirmbutton').disabled = false;
$.connection.hub.stop();
//try to send a server event. Will throw an error
//Uncaught Error: SignalR: Connection must be started before data can be sent. Call .start() before .send()
});
This is a working code that I am using:
let connection;
let connectionUrl = 'https://someurl/hubEndpoint';
connection = new signalR.HubConnectionBuilder()
.withUrl(connectionUrl)
.build();
connection.serverTimeoutInMilliseconds = 60 * 10000;
connection.on("ReceiveMessage", (message) => {
console.log(message);
// to do appropriate coding
});
connection.start().then(function () {
console.log('Connected to server');
subject = new signalR.Subject();
});
setTimeout(() => {
connection.stop().then(function() {
console.log('Closed');
connection = null;
});
}, (2000));
//Server Functions
var socketArray = [];
var socketRcon = [];
for (var i = 0; i < serversConfig.serversArray.length; i++) {
socketArray[i] = new Socket;
socketArray[i].setEncoding("utf8");
socketArray[i].setNoDelay();
socketArray[i].setTimeout(1000);
socketArray[i].connect(serversConfig.serversArray[i].port, serversConfig.serversArray[i].ip);
socketRcon[i] = serversConfig.serversArray[i].rcon;
socketArray[i].on("connect", function() {
this.write(socketRcon[i] + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
socketArray[i].on("data", function(data) {
console.log(data);
});
socketArray[i].on("error", function(err) {
console.log("ERROR:" + err);
});
socketArray[i].on("close", function(err) {
console.log("CLOSED:" + err);
});
};
This is the code I have now to connect to multiple servers from a config file, and I need that each time the socket connects, I need to send a password to it. But 'socketRcon[i]' is undefined, why is that happening and how do i fix it?
Because by the time that code is run, i is equal to serversConfig.serversArray.length, meaning socketRcon[i] is undefined.
Anchor your value:
for( var i=0; i<l; i++) (function(i) {
// do stuff here
})(i);
You could also just do:
serversConfig.serversArray.forEach(function(srvconfig) {
var sock = new Socket();
sock.setEncoding("utf8");
sock.setNoDelay();
sock.setTimeout(1000);
socketArray.push(sock);
socketRcon.push(srvconfig.rcon);
sock.on("connect", function() {
this.write(srvconfig.rcon + "\n", "utf8");
console.log("CONNECTED TO THE SERVER...");
});
sock.on("data", function(data) {
console.log(data);
});
sock.on("error", function(err) {
console.log("ERROR:" + err);
});
sock.on("close", function(err) {
console.log("CLOSED:" + err);
});
sock.connect(srvconfig.port, srvconfig.ip);
});
Need to wait for several requests to facebook to complete before taking a final action on the page (updating the count of how many requests returned info) but not sure how to approach it.
How do you check that each function is complete and update a counter before firing a function. window.load is too early unless the page is refreshed after login...?
window.fbAsyncInit = function () {
FB.init({
appId: 'id', // App ID
//channelUrl: '//facebookdev.smithbrosagency.com/LOL/xss_channel.htm', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
getStatus();
//Subscribe to events
FB.Event.subscribe('auth.statusChange', function (response) { if (response.authResponse) { getStatus(); } });
FB.Event.subscribe('auth.login', function (response) { if (response.status === 'connected') { getStatus(); } });
};
function getStatus() {
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
setPanel('results'); // connected
var accessToken = response.authResponse.accessToken;
var obj = getPermissionsObject(function (permissions) {
getUserInfo(response);
getUserPhotos(response, accessToken);
getFriends(response, accessToken);
getUserLocations(response, accessToken);
getUserMusic(response, accessToken);
getUserMovies(response, accessToken);
});
} else {
setPanel('login'); // not logged in or unauthorized
}
});
}
function getUserPhotos(response, accessToken) {
FB.api('/me/photos?access_token=' + accessToken, function (response) {
var photoList = response.data;
var len = photoList.length;
if (len >= 3) {
var max = 3;
if (len > max) { len = max }; // cap it at 3
for (var i = 0; i < len; i++) {
(function () {
var j = i;
var idx = i + 1;
$('.result2 .option' + idx + ' input').val(photoList[i].picture);
$('.result2 .option' + idx + ' img').attr("src", photoList[i].picture);
})();
}
$('div.result2').addClass("active");
$('#q2 input').val(1); // add to hidden to count results
}
else {
// hide & subtract from total questions
$('div.result2').addClass("inactive");
$('#q2 input').val(0);
}
});
}
$(window).load(function () {
$.when($('#q2 input').val() != '' && $('#q4 input').val() != '' && $('#q5 input').val() != '').then(test());
function test() {
// calc total questions
var total = 0;
$("#Results div input[hidden]").each(function () {
total += $(this).val() * 1;
});
alert(total);
}
});
I'm not sure if I understand you correctly but it seems you need to implement an object like this:
<script type="text/javascript">
//Monitoring object
function RequestStatusMonitor()
{
this.resetRequests();
}
//IDs of the requests you need to monitor
RequestStatusMonitor.prototype.requests=["firstRequest","secondRequest","thirdRequest"];
//Status of the requests
RequestStatusMonitor.prototype.requestsCompleted=[];
//Set all requests to incomplete state
RequestStatusMonitor.prototype.resetRequests = function()
{
this.requestsCompleted = [];
for(var it in this.requests)
{
this.requestsCompleted[this.requests[it]] = false;
}
}
//Set status for a request determined by requestName
RequestStatusMonitor.prototype.setRequestStatus = function(requestName, status)
{
this.requestsCompleted[requestName] = status;
}
//Check if all requests are completed
RequestStatusMonitor.prototype.allRequestsAreCompleted = function()
{
for(var it in this.requestsCompleted)
{
if(!this.requestsCompleted[it])
{
return false;
}
}
return true;
}
//----------------------------------------------------------------------------------
//Usage Example
var monitor = new RequestStatusMonitor();
function onFirstRequestFinished(/*necessary parameters*/)
{
monitor.setRequestStatus("firstRequest", true);
checkCompleted();
}
function onSecondRequestFinished(/*necessary parameters*/)
{
monitor.setRequestStatus("secondRequest", true);
checkCompleted();
}
function onThirdRequestFinished(/*necessary parameters*/)
{
monitor.setRequestStatus("thirdRequest", true);
checkCompleted();
}
function checkCompleted()
{
if(monitor.allRequestsAreCompleted())
{
//Do what you need after all requests are completed
alert("All requests are completed");
}
}
onFirstRequestFinished();
onThirdRequestFinished();
onSecondRequestFinished();
</script>