Uncaught SyntaxError: Illegal break statement within ajax - javascript

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>

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);
}
});
}

Sequential and Dynamic Number of Ajax Calls in For Loop

var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i); // 0
requests[i].apply(undefined, []);
}
});
});
console.log(i); //counts up
})(i, data);
};
requests[0].apply(undefined,[]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am wondering, how come with this code:
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: wpApiSettings.root + 'superdooperendpoint/' + apikey + "/" + data[i].start_date + "/" + data[i].end_date,
method: 'GET',
beforeSend: function(xhr) {
// Set nonce here
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
},
success: function(result) {
success_callback({
start_date: data[i].start_date,
end_date: data[i].end_date,
span: data[i].span,
result: result
});
console.log(i); // 0
requests[i].apply(undefined, []);
}
});
});
console.log(i); //counts up
})(i, data);
};
When I do the first console.log() in the success function it is always 0, not undefined, yet while outside of the success function it counts up in the iterating for loop. How can I get it to count up in the success function as well?
The following paints the updated value of i
Parallel Calls
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i);
}
});
});
})(i, data);
};
for (var i = 0; i < requests.length; i++) {
requests[i].apply(undefined, []);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Sequential Calls
var data = [{start_date:20180601,end_date:20180701},{start_date:20180801,end_date:20180901},{start_date:20181001,end_date:20181101},{start_date:20181201,end_date:20190101}];
var requests = [];
for (var i = 0; i < data.length; i++) {
(function(i, data) {
requests.push(function() {
jQuery.ajax({
url: 'https://reqres.in/api/users?page=1',
method: 'GET',
success: function(result) {
console.log(i);
i++;
if(i < requests.length) {
requests[i].apply(undefined, []);
}
}
});
});
})(i, data);
};
requests[0].apply(undefined, []);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Explanation - When you iterated over the function, for each function in requests array a value of i was passed/stored just like an argument. When you invoke the requests[0] from outside, on completion of the function, the stored value of i i.e. 0 is painted. And then, you again trigger the function stored at index = 0 i.e. you end up creating an infinite loop. In order to paint the appropriate value, loop over the requestsarray and call the individual function one by one to see the appropriate value of i being logged.
You need to assign i to a different local variable of the nested function and put the definition of i out of the block;
let i = 0;
for (; i < 100; i++) {
((n) => new Promise(
(res, rej) => setTimeout(res, 100)
).then(() => console.log(i,n))
)(i);
}

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.

JavaScript ajax success break and continue not working

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...";
}

how to summing the value from specific json object with several conditions (e.g. where value from object "TYPE" is "ABC")?

I've json like this. in that json there is object name tipe and I want to sum act_qty1, act_val1, acvqty, acvval, budqty, budval, cm_val1, cm_val2, cm_val3 in the same tipe(e.g. sum them where their tipe is "ESL"). How to sum that in javascript? can it done with loop?
here is what I've made so far:
function detail(kodenegara, koderesult)
{
$.mobile.showPageLoadingMsg();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://www.greenfields.co.id:502/Service1.svc/"+kodenegara,
dataType: "json",
success:function(data){
var result = koderesult;
var details = "";
for (i = 0; i < data[result].length; i++){
$("#"+data[result][i].tipe).empty();
}
for (i = 0, types={} ; i < data[result].length; i++){
$("#"+data[result][i].tipe).append("<tr>"+
"<td>"+data[result][i].mc+"</td>"+
"<td>"+data[result][i].value3+"</td>"+
"<td>"+data[result][i].value2+"</td>"+
"<td>"+data[result][i].value1+"</td>"+
"<td>"+data[result][i].avgqty+"</td>"+
"<td>"+data[result][i].budqty+"</td>"+
"<td>"+data[result][i].budval+"</td>"+
"<td>"+data[result][i].acvqty+"</td>"+
"<td>"+data[result][i].acvval+"</td>"+
"</tr>").trigger('create');
//----------------------------------//
// HERE IS what I've made TO SUM THE VALUES //
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv//
for(i = 0; i < data[result].length; i++) {
if(data[result][i].tipe == 'ESL')
{
//how to summing data[result][i].cm_val3 where data[result][i].tipe == 'ESL'
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
}
}
}
//show the page
$.mobile.changePage("#detail_"+kodenegara, "slide", false, true);
},
error: function () {
alert("ERROR");
}
});
}
I don't know how to write the right looping for summing the value while tipe is "ESL" (or "ESL1L" or "WHP" or else). if I use this:
var b = i + 1;
var test = parseInt(data[result][i].cm_val3) + parseInt(data[result][b].cm_val3)
that only sum the last array. how to write the right looping to sum with that condition?
Here come a working fiddle
http://jsfiddle.net/xKJn8/1/
var SumByTipe = {};
for(i in data.GetReportIdResult){
var currtipe = data.GetReportIdResult[i].tipe;
if (currtipe){
if (currtipe in SumByTipe){
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
SumByTipe[currtipe][j + '_total'] += parseFloat(data.GetReportIdResult[i][j]);
}
}
}else{
var firstSum = {};
for (j in data.GetReportIdResult[i]){
if (j != "tipe" && j != "mc"){
firstSum[j + '_total'] = parseFloat(data.GetReportIdResult[i][j]);
}
}
SumByTipe[currtipe]=firstSum;
}
}
}
console.debug(SumByTipe);
That should do the trick :
var sum_cm_val3=0;
for (var i=0;i<data[result].length;i++) {
if (data[result][i].tipe == "ESL") {
var cm_val3 = data[result][i].cm_val3;
if (parseInt(cm_val3)==cm_val3) {
sum_cm_val3 += parseInt(cm_val3);
}
}
}

Categories

Resources