clearInterval not working | undefined - javascript

I have such jQuery code and have problem with clearing intervals.
var secs = 50, width = 100;
var counter = function() {
if(secs > 0) {
secs--;
width = width - 2;
$('#time').css('width', width + '%').attr('aria-valuenow', width);
$('.seconds').html(secs);
} else if(secs == 0){
$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
clearInterval(counter);
setInterval(winner, 3000);
}
};
var winner = function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "game_results"
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "you") {
$('.waiting').addClass('hidden');
$('.you').removeClass('hidden');
} else if (data == "opponent") {
$('.waiting').addClass('hidden');
$('.opponent').removeClass('hidden');
}
}
});
console.log(clearInterval(winner)); // heer
}
function answer(question_id, answer, question) {
var question_higher = question_id + 1;
$.ajax({
type: "POST",
url: "ajax.php",
data: {
func: "play",
answer: answer,
question: question
},
error: function() {
swal("Błąd", "Serwer nie odpowiada, spróbuj ponownie", "error")
},
success: function(data) {
if (data == "wrong") {
$.playSound('build/sounds/wrong');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-danger');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
} else if (data == "correct") {
$.playSound('build/sounds/correct');
$('*[data-question="' + question_id + '"]').find('.' + answer + '').removeClass('btn-primary').addClass('btn-success');
$('*[data-question="' + question_id + '"]').find('.col-sm-12').addClass('dimmed');
setTimeout(function() {
$('*[data-question="' + question_id + '"]').addClass('hidden');
$('*[data-question="' + question_higher + '"]').removeClass('hidden');
}, 750);
}
}
});
if(question_id == 5) {
clearInterval(counter);
setTimeout(function() {
//$('.questions').addClass('hidden');
$('.results').removeClass('hidden');
}, 750);
setInterval(winner, 3000);
}
}
$(document).ready(function() {
$('*[data-question="1"]').removeClass('hidden');
setInterval(counter, 1000);
});
Im trying to get this work for almost 5 hours without results.
Both clearInterval(counter); and clearInterval(winner) are not working and flooding my server with requets.
Thanks in advance for any help.

Let's see how you're clearing the interval.
clearInterval(winner)
where, winner is the function. To clear the interval, the ID of the interval should be passed as parameter.
When setting the interval, catch the interval ID in a variable
winnerInterval = setInterval(winner, 3000);
and use this variable to clear interval.
clearInterval(winnerInterval);
Make sure the variable containing interval ID is in the scope when clearing the interval.
See clearInterval.

Related

stop the timer function from executing when form is submitted

I have an online quiz program where user needs to complete it within a time period. When user runs out of time,I show an alert saying that your time is up and he is redirected to result page. I get the same alert when user completes the quiz before the time expires and is inside result page. I have modified the code like following but its not working. I am calling the function initTimer(1,1) inside an ajax requested page named questions.php.
In index.php
function initTimer(periodInSeconds, status) {
if (status == 0) {
return false;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
var x = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(x);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});
I dont want the init function() to execute when user submits the form before time expires.Please help me
Declare the variable holding the timer outside the initTimer function, then you can clear the timer by calling it with status = 0
var timer;
function initTimer(periodInSeconds, status) {
if (status == 0) {
clearInterval(timer);
return;
}
var end = Date.now() + periodInSeconds * 1000 * 60;
timer = window.setInterval(function() {
var timeLeft = Math.floor((end - Date.now()) / 1000);
if (timeLeft < 0) {
clearInterval(timer);
alert("Time's Up!");
timeExpired = true;
var completed = 1;
$.ajax({
type: "POST",
url: "success.php",
data: {
'userID': <?php echo $_SESSION['userID'];?>
},
success: function(hasil) {
$('.response_div').html(hasil);
}
});
}
$(document).find('#timerspan').html('00:' + (timeLeft < 10 ? '0' + timeLeft : timeLeft));
}, 200);
}
//when user submits the form before time expires
$(document).on('submit', '.form_choice', function() {
initTimer(1, 0)
$.ajax({
type: "POST",
url: "result.php",
data: data,
success: function(hasil) {
$('.response_div').html(hasil);
}
})
});

Jquery ui autocomplete with barcode scanner, text is deleted on focusout

I have two input fields that come one after another:
<input class="inputItemNum ui-autocomplete-input" id="tbAutoItemCode1" name="tbAutoItemCode1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
<input class="inputItemName ui-autocomplete-input" id="tbAutoItemName1" name="tbAutoItemName1" type="text" value="" indexer="1" onkeydown="return (event.keyCode!=13);" autocomplete="off">
The first represents an item code and the other represents an item name.
On both of them I am using jquery-ui autocomplete and in 2 situations:
1) on input
2) on focus out
I need the autocomplete on focusout because I am using an android device with bar-code scanner that inserts two Tab characters as input suffix, so when reading input into the item num it does the autocomplete and when leaving the input element (with one of the tab suffix) it checks if the item num is ok (again with autocomplete - because the user might entered manually an item code that does not exists- in that case I will clean the input fields.)
Also need to mention that my autocomplete list comes from an ajax request.
The problem I am facing is that when reading the item num with the bar-code scanner it also fills in the item name (as expected) but sometimes it deletes the item name the second it was filled.
I thought it was related to the async ajax request (when the response comes back the tab suffix was already inserted and the fields were cleaned) so I tries using the ajax async:false but still no luck there. I hope someone can help me put.
here is my javascript code that uses the autocomplete:
$(document).on('input', '.inputItemNum', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 100,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ "prefixText": text, "count": 40, 'mode': 'code' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemCode,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
//openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
event.preventDefault();
//event.stopPropogation();
//focusQtyColumn(index);
focusItemNameColumn(index);
$(".ui-autocomplete").hide();
//addRow();
return false;
}
});
} // if length > 0
}); //keyup
$(document).on('keydown', '.inputItemNum', function (event) {
var code = event.keyCode || event.which;
if (code == '9') {
//alert("Tab Pressed");
event.stopPropagation();
return;
}
});
$('.inputItemNum').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
if ($(this).val() == "") { return; };
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + $(this).val() + "','count': '1','mode':'exact_code'}", //search for exact code!
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
// $("#tbAutoItemCode" + indexer).val("");
clearRowData(index);
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
})
}); //focusout
$(document).on('input', '.inputItemName', function () {
var inputId = $(this).attr("id");
var text = $(this).val();
var index = $(this)[0].attributes["indexer"].value;
if (text.length > 0) {
$(this).autocomplete({
//Alina 22-09-2016 after press a key, it takes 0ms(by default: 300ms) before it re-evaluates the dataset.
delay: 0,
focus: function () {
$(".autoCompleteItemCode").autocomplete("option", "delay", 0);
},
source: function (request, response) {
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: JSON.stringify({ 'prefixText': text, 'count': 40, 'mode': 'name' }),
dataType: "json",
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
// console.log(item);
return {
value: item.ItemName,
code: item.ItemCode,
name: item.ItemName,
price: item.ItemPrice,
multiple: item.Multiple,
vat: item.Vat,
discount: item.Discount
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert(errorThrown);
return false;
}
});
},
minLength: 1,
autoFocus: true,
select: function (event, ui) {
$("#tbAutoItemCode" + index).val(ui.item.code);
$("#tbAutoItemName" + index).val(ui.item.name);
$("#tbAutoItemPrice" + index).val(numberToCurrency(ui.item.price));
$("#tbAutoItemMultiple" + index).val(ui.item.multiple);
var l_DiscPrcnt = Math.round(ui.item.discount * 100) / 100;
$("#discount" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (ui.item.price * ui.item.multiple) - ((ui.item.price * ui.item.multiple) * (ui.item.discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(ui.item.vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * ui.item.vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(ui.item.code, ui.item.name)
return false;
});
reCalculateRow(index);
if(index == $('#orderTable tr:last').index()){
addRow();
}
return false;
}
});
} // if length > 0
}); //keyup
$('.inputItemName').live("focusout", function () {
var index = $(this)[0].attributes["indexer"].value;
var text = $(this).val().trim();
if (text.length == 0) { return };
setTimeout(function(){
//console.log("Lost focus from indexer " + indexer + " with value " + $(this).val());
$.ajax({
url: "Services/FacAjax.asmx/getCompletionItemList",
data: "{ 'prefixText': '" + text + "','count': '1','mode':'name'}", //search for name!
dataType: "json",
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (dataArr) {
if (dataArr.d.length == 0) {
$("#tbAutoItemName" + index).val("");
reCalculateRow(index);
return;
}
var data = dataArr.d[0];
$("#tbAutoItemCode" + index).val(data.ItemCode);
$("#tbAutoItemName" + index).val(data.ItemName);
$("#tbAutoItemPrice" + index).val(numberToCurrency(data.ItemPrice));
$("#tbAutoItemMultiple" + index).val(data.Multiple);
var l_DiscPrcnt = Math.round(data.Discount * 100) / 100;
$("#tbAutoItemDiscountPercent" + index).val(l_DiscPrcnt);
//round the display of discount percent to two decimal places
var l_nAfterDiscount = (data.ItemPrice * data.Multiple) - ((data.ItemPrice * data.Multiple) * (data.Discount / 100));
l_nAfterDiscount = Math.round(l_nAfterDiscount * 100) / 100;
$("#tbAutoItemAfterDiscount" + index).val(l_nAfterDiscount);
$("#tbVatPer" + index).val(data.Vat);
$("#tbItemVat" + index).val(l_nAfterDiscount * data.Vat / 100);
$("#tbAutoItemComments" + index).click(function () {
openItemDescription(data.ItemCode, data.ItemName)
return false;
});
reCalculateRow(index);
//focusItemNameColumn(index);
//focusQtyColumn(index);
$(".ui-autocomplete").hide();
return false;
}
}) }, 500);
}); //focusout
// for bar-code scanner
$(".inputItemNum").live('click', function () {
$(this).select();
});
$(".inputItemName").live('click', function () {
$(this).select();
});

jQuery AJAX 200 Undefined error with multiple / same name attributes[]

So I am submitting some data which some have the same name="" values like name="product_name[]" etc... which is why i think my current ajax is failing but not sure and not sure how to resolve. Anyone have any ideas? i.e
customer_name:James
customer_address_1:21 Test Road
customer_town:Test town
customer_postcode required:cm16 4rr
customer_email:james#email.com
customer_address_2:other part
customer_county:something
customer_phone:48486486486
customer_name_ship:James
customer_name_2_ship:other part
customer_town_ship:Test town
customer_address_1:21 Test Road
customer_county_ship:something
customer_postcode_ship:cm16 4rr
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:2
invoice_product_price[]:200
invoice_product_discount[]:20%
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:4
invoice_product_price[]:149
invoice_product_discount[]:
invoice_product[]:Versa Table - Wildberry
invoice_product_qty[]:1
invoice_product_price[]:120
invoice_product_discount[]:40
invoice_subtotal:996.00
invoice_discount:120.00
invoice_shipping:40.00
invoice_vat:199.20
invoice_total:996.00
JSFiddle: http://jsfiddle.net/90jqq4ym/
JS:
$(document).ready(function() {
// add product
$("#action_add_product").click(function(e) {
e.preventDefault();
actionAddProduct();
});
// create invoice
$("#action_create_invoice").click(function(e) {
e.preventDefault();
actionCreateInvoice();
});
// enable date pickers for due date and invoice date
var dateFormat = $(this).attr('data-vat-rate');
$('#invoice_date, #invoice_due_date').datetimepicker({
showClose: false,
format: dateFormat
});
// copy customer details to shipping
$('input.copy-input').on("change keyup paste", function () {
$('input#' + this.id + "_ship").val($(this).val());
});
// remove product row
$('#invoice_table').on('click', ".delete-row", function(e) {
e.preventDefault();
$(this).closest('tr').remove();
calculateTotal();
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table, #invoice_totals').on('change keyup paste', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
isPercent = $('[name="invoice_product_discount[]"]', tr).val().indexOf('%') > -1,
percent = $.trim($('[name="invoice_product_discount[]"]', tr).val().replace('%', '')),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0) {
if(isPercent){
subtotal = subtotal - ((parseFloat(percent) / 100) * subtotal);
} else {
subtotal = subtotal - parseFloat(percent);
}
} else {
$('[name="invoice_product_discount[]"]', tr).val('');
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal(){
var grandTotal = 0,
disc = 0;
$('#invoice_table tbody tr').each(function() {
var c_sbt = $('.calculate-sub', this).val(),
quantity = $('[name="invoice_product_qty[]"]', this).val(),
price = $('[name="invoice_product_price[]"]', this).val() || 0,
subtotal = parseInt(quantity) * parseFloat(price);
grandTotal += parseFloat(c_sbt);
disc += subtotal - parseFloat(c_sbt);
});
// VAT, DISCOUNT, SHIPPING, TOTAL, SUBTOTAL:
var subT = parseFloat(grandTotal),
vat = parseInt($('.invoice-vat').attr('data-vat-rate')),
c_ship = parseInt($('.calculate.shipping').val()) || 0,
withShip = parseInt(subT + c_ship);
$('.invoice-sub-total').text(subT.toFixed(2));
$('#invoice_subtotal').val(subT.toFixed(2));
$('.invoice-discount').text(disc.toFixed(2));
$('#invoice_discount').val(disc.toFixed(2));
if($('.invoice-vat').attr('data-enable-vat') === '1') {
if($('.invoice-vat').attr('data-vat-method') === '1') {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
} else {
$('.invoice-vat').text(((vat / 100) * subT).toFixed(2));
$('#invoice_vat').val(((vat / 100) * subT).toFixed(2));
$('.invoice-total').text((withShip + ((vat / 100) * withShip)).toFixed(2));
$('#invoice_total').val((withShip + ((vat / 100) * withShip)).toFixed(2));
}
} else {
$('.invoice-total').text((withShip).toFixed(2));
$('#invoice_total').val((withShip).toFixed(2));
}
}
function actionAddProduct(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_add_product").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#add_product").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
function actionCreateInvoice(){
if($(".required").val() == ''){
$(".required").parent().addClass("has-error");
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response .message").html("<strong>Error</strong>: It appear's you have forgotten to complete something!");
$("#response").fadeIn();
} else {
var $btn = $("#action_create_invoice").button("loading");
$.ajax({
url: 'response.php',
type: 'POST',
data: $("#create_invoice").serialize(),
dataType: 'json',
success: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-warning");
$("#response").addClass("alert-success");
$("#response").fadeIn();
$btn.button("reset");
console.log(data);
},
error: function(data){
$("#response .message").html("<strong>" + data.status + "</strong>: " + data.message);
$("#response").removeClass("alert-success");
$("#response").addClass("alert-warning");
$("#response").fadeIn();
$btn.button("reset");
}
});
}
}
});

Logic in customizing timer in java script

I have an pop up dialog that appears after every one minute and in that pop up, I have a timer that count it's time starting from 1 minute, till 0. If user presses yes in the popup dialog, the modalpop is again reset to call again after one minute.
My problem is that it was working fine until I have not introduced startBackCountDown() which creates a timer inside that modal popup. Can somebody please help me. I am stucked here.
var mins = 1;
var secs = 0;
var timer;
//240000-Four minutes
// 120000- two minutes
//60000-OneMinute
var myVar = setInterval(function () { myTimer() }, 60000);
function myTimer() {
startBackCountDown();
$("#dialog").dialog("open");
}
function startBackCountDown() {
timer = setInterval('update()', 1000);
}
function update() {
var timeField = document.getElementById('Showtime');
if (secs == 0) {
if (mins == 0) {
timeField.innerHTML = "Time's up!";
clearInterval(timer);
//alert("Time's up");
return;
}
mins--;
secs = 59;
} else {
secs--;
}
if (secs < 10) {
timeField.innerHTML = 'Time left: ' + mins + ':0' + secs;
} else {
timeField.innerHTML = 'Time left: ' + mins + ':' + secs;
}
}
function ClearTimerValues() {
window.clearInterval(myVar);
clearInterval(timer);
}
function SetTimerValuesAgain() {
var client_Name = '#Session["ClientFullName"]';
var Client_Id = '#Session["Client_LoginID"]';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../Account/ResetUser",
data: "{'User_ID':'" + Client_Id + "','Client_Name':'" + client_Name + "'}",
dataType: "json",
success: function (data) {
if (data.Data == '1') {
myVar = setInterval(function () { myTimer() }, 60000);
//window.clearInterval(timer);
mins = 1;
secs = 0;
}
else {
window.clearInterval(myVar);
window.location = "/Account/login";
}
},
error: function (xhr) {
}
});
}
$(function () {
$("#dialog").dialog({
resizable: false,
height: 140,
modal: true,
autoOpen: false,
show: "blind",
hide: "blind",
buttons: {
"Yes": function () {
SetTimerValuesAgain();
$(this).dialog("close");
},
"No": function () {
ClearTimerValues();
$(this).dialog("close");
}
}
});
});

ajax() call in javascript function

i have a jquery .click() function that executes an .ajax() method call
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value") ; //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
// alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
// alert(mediaID);
//ajax query to get link and excute code to launch music
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
when the .ajax() method executes succesfully it calls a javascript function
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
})
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
as you can see i have an .ajax() method inside my javascript function, is this possible?
I am creating loop that starts on the finish listener of the soundmanager object. So when I need to make the ajax call to get he next url I need. If my way isnt correct can you please tell me what is the best way to accomplish what i am trying to do.
Think it's fine but i would make a separate function for the ajax call so you dont need to duplicate the code twice. Easier to maintain.
$(".btn-play").live("click", function () {
//set globalSortNumber
globalSortNumber = $(this).parents("[sortnumber]").attr("sortnumber");//.attr("value"); //change should be some type of input like mediaid //see if its possible to add the sortID to the handle span
//alert(globalSortNumber);
//set title
//set mediaID
var mediaID = $(this).parents("[mediaid]").attr("mediaid");
//alert(mediaID);
//ajax query to get link and excute code to launch music
getAudio(mediaID);
}
function playsong(sortNumber,url) {
if (soundManager.supported()) {
globalSortNumber = sortNumber;
var aSoundObject = soundManager.createSound({
id: 'mySound' + sortNumber,
url: url,//'/Music/mafiamusicpt2rickross.mp3',
whileplaying: function () {
if (count == 0) {
if (this.position > 1000) {
this.pause();
pos = this.position;
count++;
this.resume();
}
} else if (count == 1) {
soundManager._writeDebug('old position: ' + pos);
soundManager._writeDebug('new position: ' + this.position);
// See that this.position is less than pos!
count++;
}
},
onfinish: function () {
//find the next song in the list
//var nextSongPosition=
this.destruct();
getAudio(mediaId);
playsong(sortNumber++,url)
}
});
aSoundObject.play();
}
}
function getAudio(mediaID) {
$.ajax({
type:"POST",
url:"ajax/AB3Ajax.asmx/GenerateLink",
data:"{'mediaId':" + mediaId + ",'userId':" + "0" + "}",
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function (msg) {
if (msg.d != "") {
playsong(msg.d,null);
}
else {
soundManager.stopAll();
//look at what is already in place in mystudio
}
},
error: function (err) {
//add code later look at what is already in place in mystudio
}
});
}

Categories

Resources