JavaScript ajax success break and continue not working - javascript

Hey guys so am testing this cracker am working on via localhost to see if i can do it really since am bored and want to do something so i thought about this but may i ask why break and continue arnt working its a for loop isnt it?, So it should work.
Edit:
Forgot to mention that the code doesnt even work when i added the break and continue.
Any help is great thanks.
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
for (var j = 0; j < pass_l_s.length; j++) {
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {'users': user_l_s[i], 'pass': pass_l_s[j]},
dataType: 'text',
async: false,
success: (function (i, j) {
return function (response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
continue;
} else if (html_next.indexOf("Cracked") > -1) {
break;
} else if (html_next.indexOf("DELETED") > -1) {
break;
}
}
})(i, j),
beforeSend: function () {
message.innerHTML = "Cracking Test...";
}
});
}
}
message.innerHTML = "Done...";
}

It is because you are sending an Async request to your server. Which means your server is handling multiple requests and it is not necessary that every request gets responded to in the same time.
What you are looking for is sequential code that can process your data all at once.
You should try async:false and then try

You have to use success callbacks, you just need to use other logic. Instead for loops, call to a function when the ajax success is complete. This function have to register the changes and, if necessary, stop or keep working.
Here is an example that I used with another SO user but the logic and the idea are the appropriate. Instead of using loops, we wait for each success callback to keep working.
var MyApp = {
Scripts: {
ToLoad: [
'/path/to/script1.js',
'/path/to/script2.js',
'/path/to/script3.js'
],
Loaded: 0
},
DoTheJob: function(){
if( this.Scripts.ToLoad.length == this.Scripts.Loaded ) {
// do some stuff
return;
}
$.getScript(this.Scripts.ToLoad[this.Scripts.Loaded], function(){
MyApp.Scripts.Loaded++;
MyApp.DoTheJob();
});
}
};
$(function(){
MyApp.DoTheJob();
});
Here is the jsFiddle

This should do it..
You can even try it out with async = true
I think so it should work with it too
function doTest() {
var html_next;
var user_l = document.getElementById("users");
var pass_l = document.getElementById("pass");
if (user_l.value == "") {
alert("The username field cant be empty!")
} else if (pass_l.value == "") {
alert("The password field cant be empty!")
}
var message = document.getElementById('status_1');
var user_l_s = user_l.value.split("\n");
var pass_l_s = pass_l.value.split("\n");
for (var i = 0; i < user_l_s.length; i++) {
num_users++;
function makeReq(pass_l_s, index) {
var index = index || 0;
$.ajax({
url: 'posttest.php',
type: 'GET',
data: {
'users': user_l_s[i],
'pass': pass_l_s[index]
},
dataType: 'text',
async: false,
success: (function(i, index) {
return function(response) {
html_next = response;
if (html_next.indexOf("Failed") > -1) {
index += 1
if (index < pass_l_s.length)
makeReq(pass_l_s, index)
// continue;
} else if (html_next.indexOf("Cracked") > -1) {
// break;
} else if (html_next.indexOf("DELETED") > -1) {
// break;
}
}
})(i, index),
beforeSend: function() {
message.innerHTML = "Cracking Test...";
}
});
}
makeReq(pass_l_s)
}
message.innerHTML = "Done...";
}

Related

Ajax multiple value

Did anyone know how i can send all this stuff with ajax to a search.php? it is already working but only with a search bar. I want to add to the search bar these variables. Its only important for the sort variable(the div with the sort id) to send the data on the beginning.
i think it would work to save the var into divs and get the values with document.getElementById('').getAttribute('value') but i still need to find out how to add this line of code to this ajax and that the ajax constantly check for changes in this divs. i still want that the ajax file send a output before i even touched the searchbar and the divs
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"post",
data:{search:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
function gettagValue() {
var checks = document.getElementsByClassName('tag');
var strtag = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
str += checks[i].value + "#";
}
}
alert(strtag);
}
function getblacklistValue() {
var checks = document.getElementsByClassName('blacklist');
var strblacklist = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strblacklist += checks[i].value + "#";
}
}
alert(strblacklist);
}
function getbrandValue() {
var checks = document.getElementsByClassName('brand');
var strbrand = '';
for ( i = 0; i<checks.length; i++) {
if ( checks[i].checked === true ) {
strbrand += checks[i].value + "#";
}
}
alert(strbrand);
}
alert(document.getElementById('sort').getAttribute('value'));
Do you mean that you want to send the values you're currently alerting? For starters, return those values instead of just alerting them:
function gettagValue() {
// ...
return strtag;
}
// same for the getblacklistValue and getbrandValue functions
Then in your AJAX code, call those functions to get those values and include them in the data:
function load_data(query)
{
let tagValue = gettagValue();
let blacklistValue = getblacklistValue();
let brandValue = getbrandValue();
$.ajax({
url:"search.php",
method:"post",
data:{
search:query,
tagValue:tagValue,
blacklistValue:blacklistValue,
brandValue:brandValue
},
success:function(data)
{
$('#result').html(data);
}
});
}

Uncaught SyntaxError: Illegal break statement within ajax

Here i'm trying to break out of a loop within an nested statement as per various questions i've seen in stackoverflow none seems to work right now code is below.
for (var i = 0; (i < 10); i++) {
var URL = "http://www.goibibo.com/hotels/search-data/?app_id=1c1cc02b&app_key=54829b227c915bd0267dec660271fa87&vcid=4675090819370906231&ci=20170720&co=20170721&r=1-1_0&pid=" + i
$.ajax({
url: URL,
type: "GET",
success: function (data) {
shareInfoLen = Object.keys(data["4675090819370906231"]).length;
if (shareInfoLen > 0) {
alert('On Process');
}
else if (shareInfoLen === 0){
alert('Closed');
break;
}
},
error: function (reponse) { }
});
}
I have used return false over break i used condition (i < 10 && j == true) and return j = false on else if condition instead of break, as i will be using infinite loop like for(var i = 0; ; i++) i need to break out of the loop if the array is 0.
Working code here.
var result = true;
for (var i = 0; i < 5; i++) {
var URL = "https://www.goibibo.com/hotels/search-data/?app_id=1c1cc02b&app_key=54829b227c915bd0267dec660271fa87&vcid=4675090819370906231&ci=20170720&co=20170721&r=1-1_0&pid=" + i
$.ajax({
url: URL,
type: "GET",
success: function (data) {
if(result){
shareInfoLen = Object.keys(data["4675090819370906231"]).length;
if (shareInfoLen > 0) {
alert('On Process');
}
else if (shareInfoLen === 0){
alert('Closed');
result = false;
}
}
},
error: function (reponse) { }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to get last instance of an array built from for loop?

I'm using a for loop to search api results and build an array of objects so I can use that data and append it to the DOM. I'm doing this because Flickr's API's results aren't consistent to their values. For example, I'm looking for "aperture" and sometimes it's index number is [9], sometimes it's [11], and so on. I'm not sure if there's another way to achieve the results I'm looking for. I figured I could just loop through the results and search for the values I need.
Is there a way to grab only the last instance of the array? As it is now if I were to call exifArray[9].aperture it would show the result multiple times and also as undefined when the loop hasn't reached that part yet. I attempted to move the console.log(exifArray) to just outside of the for loop so it wouldn't repeat but it just returns the empty array that was declared at the top of the function.
Here's a screen shot of the console and also a code snippet:
Flickr.prototype.exifData = function(results) {
var apiKey = '';
var self = this;
var exifArray = [];
for (var i=0; i<results.photos.photo.length; i++) {
var currentId = results.photos.photo[i].id;
var exifData = $.ajax({
url: "https://api.flickr.com/services/rest/?method=flickr.photos.getExif&api_key=" + apiKey + "&photo_id=" + currentId + "&format=json",
dataType: "jsonp",
jsonp: 'jsoncallback',
type: "GET",
})
.done(function(exifResults) {
var options = {};
if (exifResults.stat === "ok") {
for (var x=0; x<exifResults.photo.exif.length; x++) {
var labelArray = exifResults.photo.exif[x].label;
if (labelArray === 'Model') {
options.cameraType = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Lens Model') {
options.lensModel = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Exposure') {
options.exposure = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'Aperture') {
options.aperture = exifResults.photo.exif[x].raw._content;
} else if (labelArray === 'ISO Speed') {
options.iso = exifResults.photo.exif[x].raw._content;
} else {continue}
}
}
exifArray.push(options);
console.log(exifArray);
if (exifResults.stat === "ok") {
self.content.renderExifData(exifArray);
}
})
}
}
You can use pop()
var lastItem = arr.pop();

jQuery deferred queue in for loop

I have the following function:
function getData(a,url) {
var deferreds = [];
var i = 1;
for (i = 1; i <= a.length; i++) {
var count = i;
var back = a[i]['link'];
var path = "http://example.com";
deferreds.push(
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
delay: count
}).done(function(data) {
//success function here
}));
}
return deferreds;
}
My question is how to make this script to run a queue, for example I have 2000 requests, how to put them in a queue of 100 one by one?
Maybe in this way (Of course is a simplification)
var completed = 0;
var limit_simultaneous = 100;
var total_requests = 2134 // Assign your var
function send_block() {
for (i = 0; i < limit_simultaneous; i++) {
$.ajax({
url:path,
data:{back:back,link:url},
type:"POST",
async: true,
}).done(function(data) {
completed++;
send_next_block();
//success function here
}));
}
}
function send_next_block()
{
if (completed == limit_simultaneous && total_requests > 0) {
total_requests = total_requests - completed;
if (total_requests < limit_simultaneous) {
limit_simultaneous = total_requests;
}
completed = 0;
// Fire again
send_block(); // Send another 100
}
}
I hope it helps.
EDIT Edit to take account about the total requests. Maybe is not a working code, but it is the idea.

Delete div if no ajax info about id

i got this code
function get_players()
{
$.ajax({
type: "POST",
url: "get_players.php",
dataType: "html",
success: function(data) {
var str = data;
var chars = str.split("<br />");
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
//$('#'+chars[aimt][0]).css("top", chars[aimt][1]*32-16+"px");
//$('#'+chars[aimt][0]).css("left", chars[aimt][2]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
}});
setTimeout("get_players();", 300);
}
which receives players from this
5/7/13/GodFather
6/7/10/dsfsf
7/8/13/fdsf
and i want to ask how to delete div if there's no info about user
As you don't know which div elements to remove, the only way is removing them all then adding those you get from the AJAX response.
To remove them all, use the class that you already have:
$(".char").remove();
Add this line to the success function, before iterating over the lines.
OK, you can save the ID values returned by the AJAX call in array then remove any that does not exist in the array. Revised function code:
success: function(data) {
var str = data;
var chars = str.split("<br />");
var arrDivIDs = new Array();
for(var i = chars.length - 1; i >= 0 ;i-- ) {
chars[i] = chars[i].split('/');
arrDivIDs[chars[i][0]] = true;
var o = document.getElementById(chars[i][0]);
var aimt = i;
if (!o) {
if (aimt!=chars.length -1) {
$('#gracze').html('<div id="'+chars[aimt][0]+'" class="char"><div id="char_name" style="left:-'+(((chars[aimt][3].length*9)/2)-16)+'px;width:'+(chars[aimt][3].length*9)+'px;">'+chars[aimt][3]+'</div></div>'+$('#gracze').html());
$('#'+chars[aimt][0]).css("top", chars[aimt][2]*32-16+"px");
$('#'+chars[aimt][0]).css("left", chars[aimt][1]*32+"px");
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]+1);
}
} else {
$('#'+chars[aimt][0]).animate({
"top": chars[aimt][2]*32-16+"px", "left": chars[aimt][1]*32+"px"
}, { duration: 300});
$('#'+chars[aimt][0]).css("z-index", chars[aimt][2]);
}
}
$(".char").each(function(index) {
if (!arrDivIDs[$(this).attr("id")])
$(this).remove();
});
}
Use .remove() http://api.jquery.com/remove/
EDIT
Where you have the check to see whether there is any data coming back (assume var o) you can do this:
o.remove();
EDIT 2
You can use variables in jQuery to select the id:
$("#" + chars[i][0]).remove();

Categories

Resources