How to nested ajax call? - javascript

Here is my code.
Currently here every time inner ajax method will call when outer method mark as done.
var folderpath = encodeURIComponent('Recording' + new Date().getTime());
var ajaxWorking = true;
function uploadAudio(mp3Data) {
var reader = new FileReader();
reader.onload = function (event) {
var fd = new FormData();
var mp3Name = encodeURIComponent('audio_recording_' + new Date().getTime() + '.mp3');
console.log("mp3name = " + mp3Name);
fd.append('fname', mp3Name);
fd.append('data', event.target.result);
//Costin testing
fd.append('studentId', '1');
fd.append('folderpath', folderpath);
fd.append('recording', stopRecording)
$.ajax({
type: 'POST',
url: '/api/ClientApi/PostRecordedStream',
data: fd,
processData: false,
contentType: false,
success: function (data) {
console.log(data + " : AjaxDone");
ajaxWorking = false;
}
}).done(function (data) {
console.log(data);
//setTimeout(this, 5000);
console.log(stopRecording + " : " + ajaxWorking);
if (stopRecording == true && ajaxWorking == false) {
console.log(stopRecording + " : " + ajaxWorking + "LoadMP3");
$.ajax({
type: 'GET',
url: '/api/ClientApi/GetAudio',
data: { folderpath: folderpath },
success: function (data) {
console.log(data);
}
}).done(function (data) {
var url = 'data:audio/mp3;base64,' + data;
var li = document.createElement('li');
var au = document.createElement('audio');
var hf = document.createElement('a');
au.controls = true;
au.src = url;
hf.href = url;
hf.download = 'audio_recording_' + new Date().getTime() + '.mp3';
hf.innerHTML = hf.download;
li.appendChild(au);
li.appendChild(hf);
recordingslist.appendChild(li);
});
}
});
};
reader.readAsDataURL(mp3Data);
}
Outer ajax will call multiple time from UI. But I want to call only when all outer ajax call are done.

Related

Jquery, Why last function in script not work?

please tell me where I am making a mistake in this code, all functions except the last one are being processed, I can not understand why. The first 3 functions correctly submit the form and receive a response, the latter also submits the form, but for some reason the response opens on a new page.
jQuery(document).submit(function(e){
var form = jQuery(e.target);
var id = form.attr("action");
var ret = id.replace('/changepswd/','');
if(form.is("#changepswd")){
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changepswdbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(n){
var form = jQuery(n.target);
var id = form.attr("action");
var ret = id.replace('/changeemailpass/','');
if(form.is("#changeemailpass")){
n.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
document.getElementById("changeemailpassbtn" + ret).value = '';
alertTimeout(data,1000);
}
});
}
});
jQuery(document).submit(function(q){
var form = jQuery(q.target);
var id = form.attr("action");
var ret = id.replace('/changename/','');
var btns = document.getElementById("changenamebtn" + ret).value;
if(form.is("#changename")){
q.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Имя Успешно Изменено!"){
document.getElementById("changenamelbl" + ret).innerText = btns;
document.getElementById("changenamebtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});
jQuery(document).submit(function(o){
var form = jQuery(o.target);
var id = form.attr("action");
var ret = id.replace('/changeemail/','');
var btns = document.getElementById("changeemailbtn" + ret).value;
if(form.is("#changeemail")){
o.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
success: function(data) {
console.log(data);
if (data == "Email Успешно Изменен!"){
document.getElementById("changeemaillbl" + ret).innerText = btns;
document.getElementById("changeemailbtn" + ret).value = '';
alertTimeout(data,1000);
}
else{
alertTimeout(data,1000);
}
}
});
}
});

How to use external js script and css for custom dialog box

Could someone help me. Because I'm just started learning JavaScript.
I'm using a custom prompt dialog, before it's working when I use XMLHttpRequest
But, I want to use "Fetch" instead because it's the new one and better.
with using Fetch the dialog is not showing and I'm getting error "layer is not defined"
Here's my little question, How I can call it properly the layer.js and layer.css from the response?
I'm calling it like this (this is a message dialog):
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
Here's my code.
!function () {
try {
if (typeof (eval(layer)) == "function") { }
} catch (e) {
var css = 'https://cdn.bootcss.com/layer/3.0.1/skin/default/layer.css';
var js = 'https://cdn.bootcss.com/layer/3.0.1/layer.min.js';
var a = document.createElement("style");
a.type = "text/css";
DownloadStringAsync(css).then(_css => a.innerText = _css);
document.getElementsByTagName("head")[0].appendChild(a)
var a = document.createElement("script");
DownloadStringAsync(js).then(_js => a.text = _js);
document.getElementsByTagName("head")[0].appendChild(a)
}
var url = amp.mediaProxy.facade.config.media.originalSrc;
var title = ampl_title;
var formTitle = "Url Parser v1.0";
var msg = `${title}<br>${GetTitle()}<br>`;
try {
var fileName = `TEST.txt`;
SaveToFileAsync(url, fileName);
} catch (err) {
layer.open({
title: "Error",
content: err.message
});
}
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
async function DownloadStringAsync(url) {
let response = await fetch(url, {
method: "GET",
cache: "no-cache",
});
let data = await response.text()
return data;
}
function SaveToFileAsync(url, filename) {
fetch(url, {
method: "GET",
cache: "no-cache",
}).then(async function (t) {
const b = await t.blob();
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
});
}
function GetTitle() {
return document.getElementsByClassName("hero-image-rating eps-line")[0].innerText + "\n";
}
}();

filter by a key/value from json Array

here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});

Retrieving and Updating a Record not Working in MS CRM

this is my scenario. As I am new to Microsoft Dynamics coding, need a solution for my code.
I have two entities named Acc and Con, where Acc is parent and Con is child entity of Acc.
I have created a lookup field of Acc in Con entity along with fields with similar datatype in the two entities.
So, whenever a change in parent record is made in the fields and saved, the changes should be done automatically in the corresponding fields of the child record.
The part I get the error is to update but am able to retrieve the code. So the record fails to update.
The error I get now is
ReferenceError: FetchRecordsCallBack is not defined at Object.GetRecs.jQuery.ajax.success
Your answers and suggestions are requested and welcome. :) Here below is my code.
function accupdate() {
debugger;
var PrvdLocData;
var name;
var age;
var sex;
var address;
var phonenumber;
var degree;
var sslcpercentage;
var hscpercentage;
var ugpercentage;
var PrvdLocData = new Array();
var EmpId = Xrm.Page.data.entity.getId();
//parent fields
if (Xrm.Page.getAttribute("new_name").getValue() != null) {
name = Xrm.Page.getAttribute("new_name").getValue();
}
if (Xrm.Page.getAttribute("new_age").getValue() != null) {
age = Xrm.Page.getAttribute("new_age").getValue();
}
if (Xrm.Page.getAttribute("new_sex").getValue() != null) {
sex = Xrm.Page.getAttribute("new_sex").getValue();
}
if (Xrm.Page.getAttribute("new_address").getValue() != null) {
address = Xrm.Page.getAttribute("new_address").getValue();
}
if (Xrm.Page.getAttribute("new_phonenumber").getValue() != null) {
phonenumber = Xrm.Page.getAttribute("new_phonenumber").getValue();
}
if (Xrm.Page.getAttribute("new_degree").getValue() != null) {
degree = Xrm.Page.getAttribute("new_degree").getValue();
}
if (Xrm.Page.getAttribute("new_sslcpercentage").getValue() != null) {
sslcpercentage = Xrm.Page.getAttribute("new_sslcpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_hscpercentage").getValue() != null) {
hscpercentage = Xrm.Page.getAttribute("new_hscpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_ugpercentage").getValue() != null) {
ugpercentage = Xrm.Page.getAttribute("new_ugpercentage").getValue();
}
var context = Xrm.Page.context;
var serverurl = context.getClientUrl();
var ODatapath = serverurl + "/XRMServices/2011/OrganizationData.svc";
var retrieveResult = new XMLHttpRequest();
var dtqeurl = ODatapath + "/new_conSet?$select=new_name,new_YourAge,new_YourSex,new_HomeAddress,new_Contact,new_DegreeType,new_SSLCPercent,new_HSCPercent,new_conId,new_UGPercent&$filter=new_AccName/Id eq guid'" + EmpId + "'";
GetRecs("PrvtLoc", dtqeurl);
function GetRecs(entity, url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function XMLHttpRequest(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results, entity);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(result, entity) {
$.each(result, function () {
if (entity == "PrvtLoc")
PrvdLocData.push(this);
});
}
if (PrvdLocData.length > 0) {
for (i = 0; i < PrvdLocData.length; i++) {
//Object Assigning
var crmobject = new Object();
//Variable declaration for Child entity's primarykey (ID)
var childId = PrvdLocData[i].new_conId;
//Setting child entitiy's value with parent entity's variable
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = sex;
crmobject.new_HomeAddress = toString(address);
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = degree;
crmobject.new_SSLCPercent = sslcpercentage;
crmobject.new_HSCPercent = hscpercentage;
crmobject.new_UGPercent = ugpercentage;
// update starts...
var serverUrl = Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var crmobject = new Object();
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/new_conSet";
var jsonEntity = window.JSON.stringify(crmobject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "(guid'" + childId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("updated");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("fail to update");
}
});
}
}
}
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = { Value: sex };
crmobject.new_HomeAddress = address;
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = { Value: degree };
crmobject.new_SSLCPercent = parseFloat(sslcpercentage).toFixed(2);
crmobject.new_HSCPercent = parseFloat(hscpercentage).toFixed(2);
crmobject.new_UGPercent = parseFloat(ugpercentage).toFixed(2);

Wordpress AJAX Call can't access variables from different function

I am having issues with the scope of javascript. I cannot access these variables I define in a function.
All of the variables inside of the document.onload cannot be accessed by the uploadVideo function.
<script type="text/javascript">
document.onload = function() {
q = JQuery;
video_form = q("#wb_bc_video_form");
video_ulid = q("#wb_bc_video_ulid");
file_input = q("#wb_bc_file_input");
video_file = file_input.files[0];
video_size = q("#wp_bc_video_size");
video_time = q("#wp_bc_video_time");
};
function uploadVideo(fileFormField) {
var formdata = new FormData();
formdata.append("video", video_file);
q.ajax(
{
type: "POST",
url: ajaxurl,
beforeSend: function(xhr) {
start = new Date().getTime();
xhr.upload.addEventListener('progress', function(e) {
var loaded = e.loaded / 1048576;
var total = e.total / 1048576;
video_size.innerHTML = loaded.toPrecision(4) + "(MB / " + total.toPrecision(4) + "MB) ";
video_time.innerHTML = (new Date().getTime() - startTime) / 1000 + " Seconds";
if (Math.round(loaded) === Math.round(total)) {
node(video_form, "p", "Processing video... please wait.");
}
}, false);
}
}
).done(function(txt) {
console.log(txt);
}).fail(function(xhr, txt) {
console.log(txt);
}).always(function(xhr, txt) {
console.log(txt);
});
}
</script>

Categories