I am trying to display more than 200 videos of a custom playlist (saved in my database). I want to show the whole list in a row, using ajax, with setInterval to let Youtube API breath a bit.
Here is my code :
for(var i in a.playlist_rows) {
iTime += 100;
setTimeout(function() {
$.ajax({
url:'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id='+a.playlist_rows[i].videoID+'&key=XXX',
method:'GET',
cache:false,
dataType:'json',
success:function(a) {
callPageSuccess(a);
showIn = "playlist_content_show";
$('button#btn_play').prop('disabled', false);
$('button#btn_play_repeat').prop('disabled', false);
},
error:function() {
showError('danger', 'Erreur XHR détectée. Contactez le staff.');
}
});
}, iTime);
}
Actually, because of setInterval(), this is the last video ID that will be called in each ajax call. How to get ride of this ?
Found out the solution by passing an argument in my anonymous function :
for(var i in a.playlist_rows) {
iTime += 100;
setTimeout(function(videoID) {
$.ajax({
url:'https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails&id='+videoID+'&key=AIzaSyAHLt89IGVRiB8aAI4hUFpRFxkxQTHAqZo',
method:'GET',
cache:false,
dataType:'json',
success:function(a) {
callPageSuccess(a);
showIn = "playlist_content_show";
$('button#btn_play').prop('disabled', false);
$('button#btn_play_repeat').prop('disabled', false);
},
error:function() {
showError('danger', 'Erreur XHR détectée. Contactez le staff.');
}
});
}, iTime, a.playlist_rows[i].videoID);
}
Related
Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}
I have a problem with my add to cart ajax requests which do not result in a laravel project on which I am working. The problem is that locally everything works perfectly well:
async function add_cart(row_id,variant) {
$('#cover-spin').show(0);
$.ajax({
type: "get",
url: APP_URL + "/cart/add/" + row_id,
data: {quantity: 1,variants: variant},
success: function (response) {
if (response) {
$('#search-keyword').keyup();
refreshCartPage();
updateCartCount();
setTimeout(function(){ $('#cover-spin').hide(0); }, 1000);
toastr.options.closeButton = true;
toastr.success("Produit ajouter au panier");
} else {
refreshCartPage();
setTimeout(function(){ $('#cover-spin').hide(0); }, 1000);
toastr.options.closeButton = true;
toastr.error("Quelque chose c'est mal passé");
}
},
error: function (response) {
refreshCartPage();
setTimeout(function(){ $('#cover-spin').hide(0); }, 1000);
}
});
}
here is the link of the site in question shoppypagne.
Do you have any idea how to fix this?
Thanks in advance. :)
Okay, this is the same post as my last post which got downvoted and marked as duplicate. Here's the post again but now with the explaination why the questions from What is the cleanest way to get the progress of JQuery ajax request? didn't work.
I have an AJAX request in where I insert stuff in the database and send 2
emails. I'd like to show the progress of the AJAX request.
Currently I tried:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('title').html((100 * e.loaded / e.total) + '%');
}
});
return xhr;
},
complete: function() { /*here some stuff*/ }
});
However, it doesn't change the title during the request, but after the request it sets it to 100%. Is there any way I can get what I want? So that when 50% in the AJAX file is executed it shows 50% and does the progress like that.
The next thing I tried is:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with download progress
}
}, false);
return xhr;
},
complete: function (result){}});
However then I only get a 1 in the title, and immediately when I click my button and the AJAX gets called.
Last, I tried the second answer:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
complete: function (result) {}
}).progress(function(e, part) {
console.log(part);
}).progressUpload(function()
{
});
However this gives:
jq-ajax-progress.min.js:1 Uncaught TypeError: Cannot read property 'upload' of undefined
at Function.e.ajax (jq-ajax-progress.min.js:1)
at a.validator.submitOrderForm (checkout.js:108)
at d (jquery.validate.min.js:4)
at HTMLFormElement.<anonymous> (jquery.validate.min.js:4)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
I tried a lot of things already but none seem to work.
I have auto request using jquery ajax, I am using this function for detection new chat message & notification case. Sometimes I am thinking again what is the effect if client auto request without finish,
I am worried my server is down because i think this is like DDOS HTTP Throttling.
This is my code
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat() {
setTimeout("notifChat()" ,2000);
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg) {
//to do success
}
});
setTimeout("notifChat()" ,2000);
}
My question is
Is possible to down server or make server hung up ?
If it is not better idea any somethink suggestion ?
Note: This is not production ready code, I have not tested it.
A couple weekness of this code:
It does not handle the two http connection limit
strengths:
it can tell if the server return an error (as in server error 404,403,402....)
var failed_requests = 0;
var max = 15;
$(function(){
initChat();
});
/*
* initialize chat system
*/
function initChat()
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
function notifChat() {
$.ajax({
url: '/url',
type:"GET",
data: {id:$("#id").val()},
success:function (data,msg)
{
//to do success
},
complete: function()
{
// either call the function again, or do whatever else you want.
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
failed_requests = failed_requests + 1;
if(failed_requests < max)
{
setTimeout(
function()
{
notifChat();
}, 2000)
}
else
{
alert('We messed up');
}
}
});
}