Jquery selector when attribute data is not empty - javascript

I am having this next issue.
I am developing a calendar with date formats and therefore what I need at this point is to be able to select all elements which their data attribute is not empty, in this case the na me of the attribute is data-hueco.
<p class="huecoDisponible" data-centro="HVA" data-hueco="0000000367#20201120#161000" style="cursor:pointer;">16:10</p>
I already tried certain things such as:
if(!$('.huecoDisponible').is(":empty")){
console.log(!$('.huecoDisponible').is(":empty"));
}
This approach obviously is not working.
I also have tried another option which is:
console.log($('.huecoDisponible').attr(':not([data-hueco=""])'));
console.log($('.huecoDisponible:not([data-hueco=""])');
In this case I am not quite sure if the selection is being done appropiately.
Finally, to give you one more hint is that I am creating all of these paragraphs by this next function which is called inside an AJAX method. Inside there I am creating the html elements by appending them to 7 different id's which present every day of the week.
Every p element has two data-attributes.
function filtrarPintarNuevoHueco(result, week){
html = '';
for (var b = 0; b < 7; b++ ) {
var diaFiltro = $('#'+arr[b]).attr("data-date");
let toto = result.citas.filter(c => c.fecha == diaFiltro);
for(var i = 0; i < toto.length; i++) {
let nuevoHueco = toto[i].fecha;
let codigoCita = toto[i].numcita;
let nuevoHuecoHora = toto[i].hora;
var hour = nuevoHuecoHora.substring(0, 2);
var min = nuevoHuecoHora.substring(2, 4);
let codigoCentro = toto[i].centro;
let nuevoHuecoHoraFormatted = hour + ':' + min;
html = '<p class="huecoDisponible" data-centro="' + codigoCentro + '" data-hueco="'+ codigoCita+ '" style="cursor:pointer;">'+ nuevoHuecoHoraFormatted+"</p>" ;
$("#" + arr[b] +' div').append(html);
}
}
$('.huecoDisponible').on('click', function(e){
e.preventDefault();
e.stopPropagation();
$('.huecoDisponible').removeClass("huecoDisponible_active");
$(this).addClass("huecoDisponible_active");
let dataHueco = $(this).attr("data-hueco");
let dataCentro = $(this).attr("data-centro");
let diaNombre = $(this).parent().parent().find("h3")[0].textContent;
let diaFecha = $(this).parent().parent().find("h4")[0].textContent;
let horaCita = $(this).attr("data-hueco").split("#")[2];
let hora = horaCita.substring(0,2);
let min = horaCita.substring(2,4);
let horaFormatted = hora + ":" + min;
reservarCitaMasHuecos(dataHueco, dataCentro, diaNombre, diaFecha, horaFormatted);
});
}
const devolverHuecosSemana = (especialista, diaSapLunes) => {
$.ajax({
url: '#Url.ActionLink("HuecosLibres", "HandlerEntityDbHub")',
type: "POST",
data: {"modo":"", "centro":"", "medico": especialista.idEspecialista, "fecha": diaSapLunes }
}).done(function (result, status, xhr) {
//tenemos que comprobar que estamos en el especialista que corresponde
if (result == undefined) {
alert("Este médico no tiene huecos");
} else {
result = JSON.parse(result);
if(result.citas.length > 0){
filtrarPintarNuevoHueco(result, diasSemana.week); // IT IS CALLED INSIDE HERE, PRINTS THE APPOINTMENT FOR A CERTAIN DAY OF THE WEEK
}else{
alert("Este médico no tiene huecos");
}
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("Este médico no tiene huecos");
});
}
If anyone can give me some advice on how to proceed with the rest, it would be really appreciating.
Thanks you

Related

creating a class to be able to reduce my code and reuse it

I am a javascript student so there are things that are still not entirely clear in my head. I want to rearrange my code to make it reusable by passing it certain parameters
At this moment I have built this credit simulator, in a much longer code, it occurred to me to build a class, with that class to be able to feed the data it requires and return the values that I need to be shown on the screen.
The first method "creacionClientes" builds the profile of the credit applicant and saves it in an array, what I need is that the second method which returns a value of the fee that the person must pay, is added in the client's profile requesting the credit. Likewise, I can't find a way for the "calcularCuotas" method to feed on the information that the client variable receives, I'm very stuck and I'm drowning in a glass of water thks!
const datosTabla = document.querySelector("#tftable,tbody"); const tasas = cambiarValorTasas() let planesVisible = false;
class Clientes {
constructor (){
this.clients = []
}
creacionClientes(nombre, apellido, email, monto, plazo, tasas){
this.clients.push({
id: Date.now(),
nombre: nombre,
apellido: apellido,
email: email,
monto: monto,
plazo: plazo,
tasas: tasas,
});
}
calcularCuotas(monto, tasas, plazos){
let hoy = new Date()
let pagoMensual = 0;
let pagoAmortizacion = 0;
let pagosIntereses = 0;
pagoMensual = monto * (Math.pow(1+tasas/100, plazos)*tasas/100)/(Math.pow(1+tasas/100, plazos)-1);
while (datosTabla.firstChild){
datosTabla.removeChild(datosTabla.firstChild);
}
//creacion de fechas sucesivas
function formatoFecha(fecha) {
fecha = new Date(fecha);
var dia = fecha.getDate();
var mesIndex = fecha.getMonth()+1;
var año = fecha.getFullYear();
return dia + "/" + mesIndex + "/" + año;
}
for(let i = 1; i <= plazos; i++) {
pagosIntereses = parseFloat(monto*(tasas/100));
pagoAmortizacion = parseFloat(pagoMensual - pagosIntereses);
monto = parseFloat(monto-pagoAmortizacion);
var fechaX = hoy.setMonth(hoy.getMonth() + 1);
//creacion de las filas
$("#tablaPrestamos").append(`<tr><td>${formatoFecha(fechaX)}
<td class="valorCuota">${pagoMensual.toFixed(2)}</td>
<td>${pagoAmortizacion.toFixed(2)}</td>
<td>${pagosIntereses.toFixed(2)}</td>
<td>${monto.toFixed(2)}</td>`);
}
} }
function cambiarValorTasas (){
let plazosOpc = $("#menuPlazos").prop('selectedIndex');
let opciones = $("#menuPlazos").prop('options');
if (opciones[plazosOpc].value == 12){
$('#tasasSeleccion').html(3.95);
} else if (opciones[plazosOpc].value == 24){
$('#tasasSeleccion').html(4.19);
} else if (opciones[plazosOpc].value == 36){
$('#tasasSeleccion').html(4.36);;
}
return $('#tasasSeleccion').val(); } $(document).on('change', cambiarValorTasas);
function mostrarTabla(nombre, visibilidad ){
let mostrar = document.getElementById(nombre);
if (visibilidad == false){
if(mostrar.classList.contains("noMostrar")){
mostrar.classList.remove("noMostrar")
}
mostrar.className += " mostrar"
} else {
if(mostrar.classList.contains("mostrar")){
mostrar.classList.remove("mostrar")
}
mostrar.className += " noMostrar"
} } $('#botonCalc').on('click', (e) =>{
e.preventDefault();
mostrarTabla('tasasSeleccion', planesVisible);
mostrarTabla('tasasLabel', planesVisible);
mostrarTabla('botonEnviar', planesVisible);
mostrarTabla('tablaPrestamos', planesVisible);
planesVisible = !planesVisible;
})
$('#botonEnviar').on("click", (e) =>{
e.preventDefault();
let cliente = new Clientes();
cliente.creacionClientes($('#nombre').val(), $('#apellido').val(), $('#mail').val(), parseInt($('#aSolicitar').val()), parseInt($('#menuPlazos').val()), parseFloat(tasas))
console.log(cliente)
cliente.calcularCuotas(parseInt($('#aSolicitar').val()), tasas, parseInt($('#menuPlazos').val())) })
The problem is that you are saving the list of clients inside the client
I would try this:
Get the list of clients outside every client
Create the client on the constructor (instead of creacionClientes)
Add it to the clients list before creating the client
NOW you can use this inside calcularCuotas where the client information is stored (e.g. this.nombre)
It could be something like that
const datosTabla = document.querySelector("#tftable,tbody"); const tasas = cambiarValorTasas() let planesVisible = false;
const clientes = []
class Clientes {
constructor (nombre, apellido, email, monto, plazo, tasas){
this = {
id: Date.now(),
nombre: nombre,
apellido: apellido,
email: email,
monto: monto,
plazo: plazo,
tasas: tasas,
}
clients.push(this);
}
calcularCuotas(monto, tasas, plazos){
let hoy = new Date()
let pagoMensual = 0;
let pagoAmortizacion = 0;
let pagosIntereses = 0;
pagoMensual = monto * (Math.pow(1+tasas/100, plazos)*tasas/100)/(Math.pow(1+tasas/100, plazos)-1);
while (datosTabla.firstChild){
datosTabla.removeChild(datosTabla.firstChild);
}
//creacion de fechas sucesivas
function formatoFecha(fecha) {
fecha = new Date(fecha);
var dia = fecha.getDate();
var mesIndex = fecha.getMonth()+1;
var año = fecha.getFullYear();
return dia + "/" + mesIndex + "/" + año;
}
for(let i = 1; i <= plazos; i++) {
pagosIntereses = parseFloat(monto*(tasas/100));
pagoAmortizacion = parseFloat(pagoMensual - pagosIntereses);
monto = parseFloat(monto-pagoAmortizacion);
var fechaX = hoy.setMonth(hoy.getMonth() + 1);
//creacion de las filas
$("#tablaPrestamos").append(`<tr><td>${formatoFecha(fechaX)}
<td class="valorCuota">${pagoMensual.toFixed(2)}</td>
<td>${pagoAmortizacion.toFixed(2)}</td>
<td>${pagosIntereses.toFixed(2)}</td>
<td>${monto.toFixed(2)}</td>`);
}
} }
function cambiarValorTasas (){
let plazosOpc = $("#menuPlazos").prop('selectedIndex');
let opciones = $("#menuPlazos").prop('options');
if (opciones[plazosOpc].value == 12){
$('#tasasSeleccion').html(3.95);
} else if (opciones[plazosOpc].value == 24){
$('#tasasSeleccion').html(4.19);
} else if (opciones[plazosOpc].value == 36){
$('#tasasSeleccion').html(4.36);;
}
return $('#tasasSeleccion').val(); } $(document).on('change', cambiarValorTasas);
function mostrarTabla(nombre, visibilidad ){
let mostrar = document.getElementById(nombre);
if (visibilidad == false){
if(mostrar.classList.contains("noMostrar")){
mostrar.classList.remove("noMostrar")
}
mostrar.className += " mostrar"
} else {
if(mostrar.classList.contains("mostrar")){
mostrar.classList.remove("mostrar")
}
mostrar.className += " noMostrar"
} } $('#botonCalc').on('click', (e) =>{
e.preventDefault();
mostrarTabla('tasasSeleccion', planesVisible);
mostrarTabla('tasasLabel', planesVisible);
mostrarTabla('botonEnviar', planesVisible);
mostrarTabla('tablaPrestamos', planesVisible);
planesVisible = !planesVisible;
})
$('#botonEnviar').on("click", (e) =>{
e.preventDefault();
let cliente = new Clientes($('#nombre').val(), $('#apellido').val(), $('#mail').val(), parseInt($('#aSolicitar').val()), parseInt($('#menuPlazos').val()), parseFloat(tasas))
console.log(cliente)
clientes.push(cliente)
cliente.calcularCuotas(parseInt($('#aSolicitar').val()), tasas, parseInt($('#menuPlazos').val())) })

How to insert a function inside another function and alphabetize a phrase?

I take the opportunity to ask two things, the first I want to alphabetically order a phrase that the user previously writes but for some reason it does not finish printing the result, the second is to read the phrase and indicate if there is any repeated word and how many times it is repeated and show it On the screen of course, I wanted to do it with a function but I don't know how to put one function inside another:
Here I attach code:
var Miventana;
function AbrirVen() {
//ventana secundaria
/* pondra la ventana en el centro de la pantalla; sin importar la resolución que esté utilizando el equipo cliente.
Las variables A y H darán el tamaño a la ventana.*/
var Ancho = screen.width;
var Alto = screen.height;
var A = Ancho*50/100;
var H = Alto*50/100;
var difA = Ancho - A;
var difH = Alto - H;
var tope = difH/2;
var lado = difA/2;
var Opciones="status=no, menubar=no, directories=no, location=no, toolbar=no, scrollbars=yes, resizable=no, width="+A+", height="+H+", top="+tope+", left="+lado+"";
Miventana = open("página que vas a abrir","_blank",Opciones);
var frase = document.getElementById("frase").value;
var palabras = frase.split(" ");
var primerapalabra = palabras[0];
var ultimapalabra = palabras[palabras.length-1];
var ordenLongitud = frase.slice();
Miventana.document.write(`Primera palabra: ${primerapalabra}`,"<br>");
Miventana.document.write(`Última palabra: ${ultimapalabra}`);
var numNom = frase.length;
Miventana.document.write("</br> Tu frase tiene " + numNom + " palabras </br>");
frase.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
});
ordenLongitud.sort(function(a, b) {
return a.length - b.length
});
Miventana.document.getElementById("letras").innerHTML = 'Alfabetico: ' + frase + '<br>Longitud: ' + ordenLongitud;
function checkString(text,index){
if((text.length - index)==0 ){ //stop condition
return false;
}else{
return checkString(text,index + 1)
|| text.substr(0, index).indexOf(text[index])!=-1;
}
}
for(var frase in texts){
var text = texts[frase].split("");
Miventana.document.write(text + " -> " + text.some(function(v,i,a){return a.lastIndexOf(v)!=i;}) +"<br/>");
}
}
I want to alphabetically order a phrase that the user previously writes but for some reason it does not finish printing the result
You're sorting the wrong variable. You should sort the palabras variable, which is an array containing the splitted words rather than frase, which is the string.
var Miventana;
function AbrirVen() {
// [...]
var frase = document.getElementById("frase").value;
var palabras = frase.split(" ");
var primerapalabra = palabras[0];
var ultimapalabra = palabras[palabras.length-1];
var ordenLongitud = frase.slice();
Miventana.document.write(`Primera palabra: ${primerapalabra}`,"<br>");
Miventana.document.write(`Última palabra: ${ultimapalabra}`);
var numNom = frase.length; // <<< this should be palabras.length (not `frase`)
Miventana.document.write("</br> Tu frase tiene " + numNom + " palabras </br>");
frase.sort(function (a, b) { // <<< again you should sort palabras
return a.toLowerCase().localeCompare(b.toLowerCase());
});
// [...]
}
the second is to read the phrase and indicate if there is any repeated word and how many times it is repeated and show it
You could do that by using an object which holds the counts for each word (I took that approach from How to count duplicate value in an array in javascript):
var counts = {};
palabras.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
for (k in counts) {
if (counts[k] > 1) {
// Show the output however you like
console.log(`Word '${k}' appears ${counts[k]} times`)
}
}
Finally:
I wanted to do it with a function but I don't know how to put one function inside another
There's no problem at all with defining a function inside another function. We could take the counting lines above, abstract them into a function and just call it from AbrirVen():
var Miventana;
function AbrirVen() {
// [...]
var frase = document.getElementById("frase").value;
var palabras = frase.split(" ");
// [...]
function displayCounts(words_to_be_counted) {
var counts = {};
words_to_be_counted.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
for (k in counts) {
if (counts[k] > 1) {
// Show the output however you like
console.log(`Word '${k}' appears ${counts[k]} times`)
}
}
}
displayCounts(palabras)
// [...]
}

JQuery function doesnt work after an other does

this code is from a cart of a music store I have made. The problem is that I need to check if the quantity I choose in the cart is in available in the stock. It works but if the user changes the quantity in the input number, the button pagar(pay) doesnt work. If I reaload the page it works but I need to do it without reload. The code:
$("#pagar").click(function() {
var tt_precio = $("#t_compra").text();
//solo cojo el precio tt y le quito el €;
var tt_precio = tt_precio.split(" ")[4];
var tt_precio = tt_precio.slice(0, -1);
var precios = [];
var fecha = new Date();
var date =
fecha.getFullYear() +
"/" +
Number(fecha.getMonth() + 1) +
"/" +
fecha.getDate();
$("[id*=precios]").each(function() {
var p = $(this)
.text()
.slice(0, -1);
precios.push(p);
});
var cantidades = [];
$("[type = number]").each(function() {
cantidades.push(Number($(this).val()));
});
var referencias = [];
$("[id*=referencias]").each(function() {
referencias.push($(this).text());
});
var nombres = [];
$("[id*=nombres]").each(function() {
nombres.push($(this).text());
});
var datos = {
precios: JSON.stringify(precios),
cantidades: JSON.stringify(cantidades),
referencias: JSON.stringify(referencias),
nombres: JSON.stringify(nombres),
tt_precio: tt_precio,
fecha: date
};
$.ajax({
type: "post",
data: datos,
url: "compra.php",
success: function(vuelta) {
alert(vuelta);
window.location.href = "/AccesoDatos/index.php";
}
});
});
$("seguir")
//cambiar precios
$("input").change(function() {
var valor = $(this).val();
var id = $(this).attr("id");
//para eliminar el simbolo del €
var precio = $("#precios" + id)
.text()
.slice(0, -1);
var datos = {
cantidad: valor,
referencia: id,
precio: precio
};
$.ajax({
type: "post",
data: datos,
url: "modificarCantidades.php",
success: function(datos) {
if (datos == -1) {
$("#span" + id).html("No hay suficientes unidades");
} else {
if (datos == 0) {
$("#fila" + id).remove();
$("#t_compra").html("0€");
$("#precio").html("0");
} else {
$("#span" + id).html("");
var precio = $("#precios" + id)
.text()
.slice(0, -1);
var cantidad = datos;
var total = precio * cantidad;
$("#total" + id).text(total + "€");
//alert(total);
var total_precio = 0;
var total_Cantidad = 0;
// coge todos los elementos que contienen en el id la palabra total y suma su valor
$("[id*=total]").each(function() {
var p = Number(
$(this)
.text()
.slice(0, -1)
);
total_precio += p;
});
//coge los inputs number para sumarlos
$("[type = number]").each(function() {
var c = Number($(this).val());
total_Cantidad += c;
});
//meto los valores nuevos en su sitio; --> en ajax hay que modificar el array de sesiones.
$("#unidades").html(total_Cantidad);
$("#precio").html(total_precio);
$("#t_productos").html(
"<strong>Total productos:</strong>" + total_Cantidad + "UDS"
);
$("#t_compra").html(
"<strong>Total de la compra:</strong>" + total_precio + "€"
);
}
}
}
});
});
It work clicking a button the first one and changing some input type="number", the problem is that if I use the onChange function, then I need to pay the updated cart but it is not posible because the button pay function doesn't work, I dont know why, I've tested whit an alert() at the top of the function, just below the call and it works but doesnt happend from there.
Change the below function:
$("input").change(function() {
For input field types change trigger function should not be used, try changing it with keyup function with 5 sec delay.
That might can help you out.
I have done something similar to this while you can use after doing some changes into it according to your need:-
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 2000; //time in ms, 5 second for example
var $input = $('#user_name');
//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$input.on('keydown', function () {
clearTimeout(typingTimer);
});
I've solved it, the problem was that the variable tt_precio was not set, when I click the button it does nothing because I dont update that value

Clear interval when condition is true ajax and jquery

I'm trying to clear an interval calling the function to check the condition inside an ajax but every 5 seconds I'm still getting the message so the interval is not cleared. What am I doing wrong? I call the function inside the ajax 'update tarea' and I send the interval name and the checked condition but the interval is still running
function update_task(update_tarea, interval){
if(update_tarea === "si"){
window.clearInterval(interval);
swal({
title: "Se ha fijado el próximo recordatorio",
icon: "success"
});
}
}
//get info profile
$.ajax({
url: 'recordatorio.php',
type: 'post',
data: { iduser: iduser},
dataType: 'json',
success: function (response) {
if(response.validacion === "ok"){
var tareas = response['mascotas'];
var fecha = new Date();
var mes = fecha.getMonth() + 1;
var dia = fecha.getDate();
var año = fecha.getFullYear();
var fechaHoy = año + '-' + mes + '-' + dia;
var len = tareas.length;
for(i=0; i<len; i++){
var fechaTarea= tareas[i]['fecha'];
var idpetTarea = tareas[i]['idpet'];
var idtipo = tareas[i]['idtipo'];
var notas = tareas[i]['notas'];
var horaTarea = tareas[i]['hora'];
var tipotarea = tareas[i]['tipo'];
var nombremascota = tareas[i]['petname'];
if(fechaHoy === fechaTarea){
var interval= idtipo+idpetTarea+"interval";
window.interval = setInterval(function () {
var hH = new Date();
var horas = hH.getHours();
var minutos = hH.getMinutes();
var segundos = hH.getSeconds();
var horaHoy = horas + ':' + minutos + ':' + segundos;
var string= "Recuerda la tarea <b>''"+tipotarea+"''</b> para tu mascota <b>"+nombremascota+"</b></br>Notas:"+notas;
if(horaHoy === horaTarea || horaHoy > horaTarea){
swal({
title: "Recordatorio",
text: "Recuerda la tarea <b>''"+tipotarea+"''</b> para tu mascota <b>"+nombremascota+"</b></br><b>Notas</b>:"+notas,
html: true,
icon: "info"
});
//update tarea
window.update_tarea;
$.ajax({
url: 'updatetarea.php',
type: 'post',
data: { idpetTarea: idpetTarea, idtipo: idtipo },
dataType: 'json',
async : false,
success: function (response) {
if(response === "ok"){
update_tarea= "si";
update_task(update_tarea, interval);
}
}
});
}
}, 5000); //end interval
}
}
}
}
});
Try outputting the value of interval in your callback function to the console. I think you'll see the same value each time.
Since you're setting the interval in a loop, you're getting multiple intervals but you only have a pointer to one of them. Each time you set the callback function and passing it interval, it's passing the same interval. Try using bind() if that's the case.

Correct order in for loop using Parse

I want to create a array containing objects, and I'm using Parse to query all the data.
However, the for loop which loops over the results doesn't does that in the correct order but randomly loops over the data. If I log i each iteration, the logs show different results every time.
Here is my code:
for (var i = 0; i < results.length; i++)
{
Parse.Cloud.useMasterKey();
// retrieve params
var objectid = results[i];
var self = request.params.userid;
// start query
var Payment = Parse.Object.extend("Payments");
var query = new Parse.Query(Payment);
query.get(objectid, {
success: function (payment) {
// get all the correct variables
var from_user_id = payment.get("from_user_id");
var to_user_id = payment.get("to_user_id");
var amount = payment.get("amount");
var createdAt = payment.updatedAt;
var note = payment.get("note");
var img = payment.get("photo");
var location = payment.get("location");
var status = payment.get("status");
var fromquery = new Parse.Query(Parse.User);
fromquery.get(from_user_id, {
success: function(userObject) {
var fromusername = userObject.get("name");
var currency = userObject.get("currency");
var toquery = new Parse.Query(Parse.User);
toquery.get(to_user_id, {
success: function(touser)
{
var tousername = touser.get("name");
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
},
error: function(touser, error)
{
var tousername = to_user_id;
if(tousername !== null || tousername !== "")
{
sendArray(tousername);
}
}
});
function sendArray(tousername) {
var array = new Array();
// create the time and date
var day = createdAt.getDate();
var year = createdAt.getFullYear();
var month = createdAt.getMonth();
var hour = createdAt.getHours();
var minutes = createdAt.getMinutes();
// create the timestamp
var time = "" + hour + ":" + minutes;
var date = "" + day + " " + month + " " + year;
var associativeArray = {};
if(self == from_user_id)
{
fromusername = "self";
}
if(self == to_user_id)
{
tousername = "self";
}
associativeArray["from"] = fromusername;
associativeArray["to"] = tousername;
associativeArray["amount"] = amount;
associativeArray["currency"] = currency;
associativeArray["date"] = date;
associativeArray["time"] = time;
associativeArray["status"] = status;
if(note == "" || note == null)
{
associativeArray["note"] = null;
}
else
{
associativeArray["note"] = note;
}
if(img == "" || img == null)
{
associativeArray["img"] = null;
}
else
{
associativeArray["img"] = img;
}
if(location == "" || location == null)
{
associativeArray["location"] = null;
}
else
{
associativeArray["location"] = location;
}
array[i] = associativeArray;
if((i + 1) == results.length)
{
response.success(array);
}
},
error: function(userObject, error)
{
response.error(106);
}
});
},
error: function(payment, error) {
response.error(125);
}
});
}
But the i var is always set to seven, so the associative arrays are appended at array[7] instead of the correct i (like 1,2,3,4,5)
The reason that this is so important is because I want to order the payment chronologically (which I have done in the query providing the results).
What can I do to solve this issue?
Success is a callback that happens at a later point in time. So what happens is, the for loop runs 7 times and calls parse 7 times. Then after it has run each of parse success calls will be executed, they look at i which is now at 7.
A simple way to fix this is to wrap the whole thing in an immediate function and create a new closure for i. Something like this
for(var i = 0; i < results.length; i++){
function(iClosure) {
//rest of code goes here, replace i's with iClosure
}(i);
}
Now what will happen is that each success function will have access to it's own iClosure variable and they will be set to the value of i at the point they were created in the loop.

Categories