How to disable form button until function has fully complete - javascript

So everything in script works perfectly. However there is an issue in this part of the code:
var min = 1;
while (min < 200) {
var max = min + 30;
scan(fruitID, min, max);
var min = max;
}
What I want from this loop:
Computes max value
Calls scan() function
Waits until the ajax in scan has successfully gotten the data, and displayed it up on the screen.
Computes min value
Repeats the loop
The mistake is in step 3. It doesn't wait for ajax to get the data back and process it. It just straight away repeats the loop. How do I make the loop wait until the scan() function has fully finished.
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {fruitName:fruitName},
success : function(data){
if (data.code == 200){
$("#submit").html("Running Scan");
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
var min = 1;
while (min < 200) {
var max = min + 30;
scan(fruitID, min, max);
var min = max;
}
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>"+data.msg+"</ul>");
$(".display-error").css("display","block");
}
}
});
});
});
function scan(vFruitId, min, max) {
$.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {vFruitId: vFruitId, min: min, max: max},
success : function(data){
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div>
`);
})
}
});
}
<form>
<label for="fname">Fruit (only correct input is: banana)</label><br>
<input type="text" id="fruit-name" name="fruit" value="banana"><br>
<button type="submit" id="submit" value="Submit">Submit</button>
</form>
<div id="results">
</div>

note: your original code does not re-enable the form button, so the question title is a bit misleading
The solution is to use the Promise-like object returned by $.ajax
The following code uses arrow notation like in the question, but does not use async/await so would work anywhere the code in the question works
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
$("#submit").attr("disabled", true);
$("#submit").html("Verifying Username");
var fruitName = $("#fruit-name").val();
$.ajax({
type: "POST",
url: "verify-input.php",
dataType: "json",
data: {
fruitName: fruitName
},
success: function (data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
function runscan(min) {
return scan(fruitID, min, min+30)
.then(() => {
min = min + 30;
if (min < 200) {
return runscan(min);
}
});
}
runscan(1)
.then(() => {
// all done here
});
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
});
});
});
function scan(vFruitId, min, max) {
return $.ajax({
type: "POST",
url: "scanner.php",
dataType: "json",
data: {
vFruitId: vFruitId,
min: min,
max: max
},
success: function (data) {
data.forEach((item, idx) => {
$("#results").append(`
<div class="fruit-item" data-item="${idx}">
<div class="f-calories">calories: ${item.sweetness}</div>
<div class="f-sweetness">sweeteness: ${item.calories}</div>
<div class="f-bitterness">bitterness: ${item.bitterness}</div>
</div>
`);
})
}
});
}
Alternatively, using async/await, the main success code can be written
success: function(data) {
if (data.code == 200) {
$("#submit").html("Running Scan");
(async function() { // `success` can't be async, because jquery doesn't like that
var fruitID = data.fruitId;
//alert("Fruit ID: " + fruitID);
var min = 1;
while (min < 200) {
await scan(fruitID, min, min + 30);
min = min + 30;
}
})();
} else {
$("#submit").attr("disabled", false);
$("#submit").html("Submit");
$(".display-error").html("<ul>" + data.msg + "</ul>");
$(".display-error").css("display", "block");
}
}
Important note: you still MUST return $.ajax in function scan as per first code snippet

Related

How to run a function that a on form submit ajax with automatic click button

I am trying to submit a form with just automatic click button.
so I have a timer which is if the timer is already 0, it should submit the form automatically.
here is the code that I have.
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
if (sec < 10) {
sec = '0' + sec;
}
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
//boolean is false
if (secondsRemaining === 0) {
submitAnswer();
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
function submitAnswer() {
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
method: "post",
url: url,
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
});
}
How can I run the submitAnswer function if the timer is already 0. any help would be really appreciated.
The submitAnswer() function just attaches the event handler, it doesn't actually submit the form.
To achieve what you require attach the submit event handler when the page loads, then when you want to submit the form trigger that event on it. Try this:
// attach submit event handler when the page loads
$('#form_question_scenario').on('submit', function(e) {
$.ajax({
// ajax settings here...
});
});
function tick() {
var timeDisplay = document.getElementById('question_timer');
var isTimeLimit = true;
var min = Math.floor(secondsRemaining / 60);
var sec = ('00' + (secondsRemaining - (min * 60))).slice(-2); // note tidied the logic here
var message = min.toString() + ':' + sec;
timeDisplay.innerHTML = message;
// stop if down to zero
if (secondsRemaining === 0 && isTimeLimit == true) {
clearInterval(intervalHandle);
displayQuestion();
} else {
if (secondsRemaining === 0) {
$('#form_question_scenario').trigger('submit'); // submit the form here
clearInterval(intervalHandle);
}
}
secondsRemaining--;
}
function startCountdown() {
clearInterval(intervalHandle);
secondsRemaining = 5;
intervalHandle = setInterval(tick, 1000);
}
You don't need submit event at all, just call the function like you did when 0 sec is left, get id of form and create new form data, and do Ajax request...
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
$.ajax({
method: "post",
url: url,
data: new FormData(myForm),
dataType: "json",
contentType: false,
cache: false,
processData: false,
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding / update data');
}
});
}
EXAMPLE:
Form data is populated without submit event just by calling the function:
function submitAnswer() {
let myForm = document.getElementById('form_question_scenario');
let data = new FormData(myForm)
formObj = {};
for (var pair of data.entries()) {
formObj[pair[0]] = pair[1]
}
console.log(formObj)
}
submitAnswer()
<form id="form_question_scenario">
<input type="text" value="test" name="test">
</form>

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

How to make my ajax polling run for 5 times only then terminate

I want to do is do now is instead of infinite ajax polling i want to do is make it run for 5 times then terminate the ajax infinite polling.
My problem is it doesn't work as i wanted. Can anyone help me with this?
ajax script:
$(document).ready(function () {
var = x;
var countTimer = setInterval(function () {
if(x++ === 5){
clearInterval(countTimer);
}else{
codeValue()
}
}, 500)
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});
Change to var x = 0
I'd personally do it like this:
var x = 0;
var countTimer = setInterval(function () {
if(x === 5){
clearInterval(countTimer);
}else{
codeValue();
x++;
}
}, 500);
First of all you do not define x, u have var = x; which should be a syntax error. Try this:
$(document).ready(function () {
var countTimes = 0;
var numberOfTimes = 5;
var countTimer = 0;
countTimer = setInterval(function () {
countTimes++;
if(countTimes > numberOfTimes){
clearInterval(countTimer);
}else{
codeValue();
}
}, 500);
function codeValue() {
$.ajax({
type: "POST",
url: 'codeTime.php',
dataType: "JSON",
cache: false,
success: function (result) {
$("#count").val(result.user_code);
}
});
return false;
}
});

Ajax Chrome wont evaluate script immediately in success

I have this source:
$("#allDataForm").submit( function (e) {
e.stopPropagation();
var formData = $("#allDataForm").serialize();
var count = formData.substring(formData.indexOf('&count=')+7,formData.indexOf('&x='));
var x = parseInt(formData.substring(formData.indexOf('&x=')+3, formData.length));
if (formData.indexOf('=description&') > 0 &&
formData.indexOf('=name&') > 0 &&
formData.indexOf('=identifier&') > 0) {
var head = 0;
if (formData.indexOf('firstashead=on') > 0) {
head=1;
}
head = parseInt(head);
var imported = 0;
var updated = 0;
$("#assignTable").hide();
$("#send").hide();
$("#status").show();
var totalTime = 0;
if (count > 0) {
for (s=x; s<=count; s++) {
var startms = new Date().getTime();
$.ajax({
type: "POST",
data: formData,
dataType: "html",
url: "/import/universalimport/",
async: false,
success: function(msg, textStatus, XMLHttpRequest) {
console.log($.makeArray(arguments), 'success');
console.log(textStatus, 'success1');
console.log(XMLHttpRequest, 'success2');
if (msg == 'imported') {
imported = parseInt(imported)+1;
} else if (msg == 'updated') {
updated = parseInt(updated)+1;
}
var endms = new Date().getTime();
totalTime = totalTime + (endms-startms);
x = totalTime / 1000;
tSeconds = Math.abs((x % 60).toFixed(0));
if (tSeconds < 10) {
tSeconds = 0+String(tSeconds);
}
x /= 60;
tMinutes = Math.abs((x % 60).toFixed(0));
if (tMinutes < 10) {
tMinutes = 0+String(tMinutes);
}
x /= 60;
tHours = Math.abs((x % 24).toFixed(0));
if (tHours < 10) {
tHours = 0+String(tHours);
}
x = (totalTime*(count-s-head)/s) / 1000;
aSeconds = Math.abs((x % 60).toFixed(0));
if (aSeconds < 10) {
aSeconds = 0+String(aSeconds);
}
x /= 60;
aMinutes = Math.abs((x % 60).toFixed(0));
if (aMinutes < 10) {
aMinutes = 0+String(aMinutes);
}
x /= 60;
aHours = Math.abs((x % 24).toFixed(0));
if (aHours < 10) {
aHours = 0+String(aHours);
}
eval($("#bar").css('width', (parseInt(s)/parseInt(count)*100).toFixed(2) + '%'));
$("#bar").html((parseInt(s)/parseInt(count)*100).toFixed(2) + '%');
$("#imported").html(imported);
$("#updated").html(updated);
$("#summary").html(imported+updated);
$("#count").html(count-head);
$("#elapsed").html(tHours + ':' + tMinutes + ':' + tSeconds);
$("#remaining").html(aHours + ':' + aMinutes + ':' + aSeconds);
formData = formData.substring(0, formData.indexOf('&x=')+3) + parseInt(s);
}
});
}
}
} else {
alert('Pro provedení importu je nutno napárovat minimálně Název, Popis a Identifikátor!');
}
return false;
});
In Google Chrome it wont evaluate script inside success immediately but after all ajax calls it execute the last one. When I add alert() inside success it works fine and in Firefox it works well.
Async is a depreciated feature. Success is also on its way out. You should be using
$.ajax({
type: "POST",
data: formData,
dataType: "html",
url: "/import/universalimport/"
}).done(msg, textStatus, XMLHttpRequest) {
... rest of code when done here
Here is a jsfiddle showing a set of $.ajax() POSTs being sent all at once and coming back at different intervals:
<ul id='log'></ul>
<script>
var call,
log = $('#log');
for (call = 0; call < 10; call++) {
$.ajax({
type: 'POST',
url: '/echo/html/',
data: {
html: "ajax response #" + call,
delay: 3
},
success: function(data) {
log.append('<li>'+data+'</li>')
console.log(data);
},
dataType: 'html'
});
log.append('<li>'+('ajax request #' + call)+'</li>')
console.log('ajax request #' + call);
}
</script>
I've run this in Chrome and Firefox and the behavior appears to be the same (the ajax responses return out of order as though they had been submitted at different intervals). Does this model the problem you are talking about?
Solved by recursive calling asynchronous ajax. Thanks for help.

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