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.
Related
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
When 5 cards are created for the 5-day weather forecast, the icon, temp, and humidity data are correct, but the date stays the same on all five cards. Any idea why? Thank you!
UPDATE: I added "if-sentence" realizing that the data I get is for every few hours so that`s the reason my cards all have the same date. This syntax seems logical to me, but it ends up giving me only one card. I hope someone can spot the error in my code. Thank you.
$(document).ready(function() {
$("#submit").on("click", function() {
var userInput = $("#user-input").val();
fiveDayForecast(userInput);
});
var key = 'my API key';
var url = "https://api.openweathermap.org/data/2.5/forecast";
function fiveDayForecast(userInput) {
$.ajax({
url: url,
dataType: "json",
type: "GET",
data: {
q: userInput,
appid: key,
units: "imperial",
cnt: "5"
},
success: function(data) {
$("#five-day-forecast").empty();
for (var i = 0; i < data.list.length; i++) {
if(data.list[i].dt_txt.indexOf("15:00:00") !== -1) {
var colEl = $("<div>").addClass("col col-lg-2");
var cardEl = $("<div>").addClass("card text-white bg-primary m-3");
var cardBody = $("<div>").addClass("card-body");
var cardTitle = $("<h5>").addClass("card-title").text(new Date(data.list[i].dt_txt).toLocaleDateString());
var img = $("<img>").attr("src", "http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png");
var cardText1 = $("<p>").addClass("card-text").text("Temp: " + data.list[i].main.temp_max + " °F");
var cardText2 = $("<p>").addClass("card-text").text("Humidity: " + data.list[i].main.humidity + "%");
colEl.append(cardEl.append(cardBody.append(cardTitle, img, cardText1, cardText2)));
$("#five-day-forecast").append(cardEl);
}
}
}
})
}
});
Sample data:
"list":[
{ "dt":1595840400, "main":{}, "weather":[], "clouds":{}, "wind":{}, "visibility":10000, "pop":0.66, "rain":{},
"sys":{}, "dt_txt":"2020-07-27 09:00:00"
},
...
]
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
I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: {
"ACCEPT": "application/json;odata=verbose"
},
success: function(data) {
for (i = 0; i < data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if (data.d.results[i]['Name'] != null) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>
I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>