Wordpress AJAX Call can't access variables from different function - javascript

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>

Related

How to calculate response and callback time in the case of AJAX Call?I'm calculating this using a js file and a html file. index.html part

<script >
$( document ).ready(function() {
$("#acall").click(function() {
startTime = new Date().getTime();
localStorage.setItem('startTime', startTime);
var ajaxTime= new Date().getTime();
/* var dataLength = JSON.stringify(data).length; */
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts',
/* url: 'http://192.168.0.101:9090/Lab/login?username=usre&password=usre', */
// data: { get_param: 'value' },
dataType: 'text',
async : true,
start_time: new Date().getTime(),
success: function (data, msg) {
//alert(data);
//console.log('This request took '+(new Date().getTime() - this.start_time)+' ms');
/* document.getElementById("demo").innerHTML = data; */
document.getElementById("demo").innerHTML = msg;
var ajaxEnddd = new Date().getTime();
/* console.log("Hello"); */
document.getElementById("demorst").innerHTML ="Ajax Response Time: "+localStorage.getItem('rst')+" ms";
document.getElementById("democbt").innerHTML ="Ajax Callback Time: "+(ajaxEnddd - localStorage.getItem('rs4date'))+" ms";
}
})
/* var ajaxEnd = new Date().getTime();
document.getElementById("demom").innerHTML = ajaxEnd - ajaxTime; */
});
});
</script>
// And the js file is
XHR.prototype.send = function(data) {
var xhr = new XMLHttpRequest();
var self = this;
var start;
var oldOnReadyStateChange;
var url = this._url;
if (self.readyState == 1){
var rs1date = new Date().getTime();
localStorage.setItem('rs1date', rs1date);
}
function onReadyStateChange() {
if(self.readyState == 4 && self.status == 200) {
var rs4date = new Date().getTime();
localStorage.setItem('rs4date', rs4date);
var rst = (localStorage.getItem('rs4date')-localStorage.getItem('rs1date'));
localStorage.setItem('rst',rst);
}
//From html file when I'm doing ajax call it calling js file too, and I
And the js file is
I'm calculating this using a js file and a html file.
index.html part
<script type="text/javascript">
$( document ).ready(function() {
$("#acall").click(function() {
startTime = new Date().getTime();
localStorage.setItem('startTime', startTime);
var ajaxTime= new Date().getTime();
/* var dataLength = JSON.stringify(data).length; */
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts',
/* url: 'http://192.168.0.101:9090/Lab/login?username=usre&password=usre', */
// data: { get_param: 'value' },
dataType: 'text',
async : true,
start_time: new Date().getTime(),
success: function (data, msg) {
//alert(data);
//console.log('This request took '+(new Date().getTime() - this.start_time)+' ms');
/* document.getElementById("demo").innerHTML = data; */
document.getElementById("demo").innerHTML = msg;
var ajaxEnddd = new Date().getTime();
/* console.log("Hello"); */
document.getElementById("demorst").innerHTML ="Ajax Response Time: "+localStorage.getItem('rst')+" ms";
document.getElementById("democbt").innerHTML ="Ajax Callback Time: "+(ajaxEnddd - localStorage.getItem('rs4date'))+" ms";
}
})
/* var ajaxEnd = new Date().getTime();
document.getElementById("demom").innerHTML = ajaxEnd - ajaxTime; */
});
});
</script>
And the js file is
XHR.prototype.send = function(data) {
var xhr = new XMLHttpRequest();
var self = this;
var start;
var oldOnReadyStateChange;
var url = this._url;
if (self.readyState == 1){
var rs1date = new Date().getTime();
localStorage.setItem('rs1date', rs1date);
}
function onReadyStateChange() {
if(self.readyState == 4 && self.status == 200) {
var rs4date = new Date().getTime();
localStorage.setItem('rs4date', rs4date);
var rst = (localStorage.getItem('rs4date')-localStorage.getItem('rs1date'));
localStorage.setItem('rst',rst);
}
//From html file when I'm doing ajax call it calling js file too, and I
//From html file when I'm doing ajax call it calling js file too, and I
Usually, when you want to know how much time take your request, you use something like this :
const dateBegining = Date.now()
fetch("https://swapi.co/api/planets/3/")
.then(response => response.json())
.then(j => {
const dateEnding = Date.now()
console.log(`The API call took ${dateEnding - dateBegining} ms`)
console.log(j)
})

How to nested ajax call?

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.

Multiple Javascript functions, need confirm dialog before executing any

I have three separate javascript/jquery functions, all of which fire off after the user clicks a button. One function posts to a form handler. Another function creates a new tab. And the third function grabs the id of the new tab and posts sends new information into the tab via an ajax call. They all work together and depend on one another.
I have tried many different configurations, and I cannot figure out how to properly get a confirmation dialog (e.g., "Do you want to perform this action?) to work with all three of these simultaneously. If the user clicks "yes," the process should fire. If the user clicks "no," the process should die. Any help is greatly appreciated.
Edit: I've posted my code below. I'm sure it's really noobish, which is why I didn't post it the begin with. Trying to learn though. Thanks!
jQuery(".update_form").click(function(e) { // changed
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
return false; // avoid to execute the actual submit of the form.
});
jQuery(".update_form").click(function () {
var form = jQuery(this).parents('form:first');
title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
});
jQuery(".update_form").click(function (e) {
e.preventDefault();
//var j = jQuery.noConflict();
var form = jQuery(this).parents('form:first');
var fileName = jQuery("input[name='process']", form).val();
jQuery(document).ready(function () {
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
jQuery("#"+ tabID).everyTime(1000, function (i) {
if (stopMe != 2){
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
if (html === oldhtml){
isSame++;
if (isSame === 10){
stopMe = 2;
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
});
});
This is what I ended up doing. I basically combined all the functions into one big function.
var panelIds = new Array();
panelIds.push('0');
jQuery(".update_form").click(function (e) {
if (confirm('Are you sure?')) {
e.preventDefault();
jQuery.ajax({
type: "POST",
url: "/eemcontrolpanel/process.cshtml",
data: jQuery(this).parent().serialize() // changed
});
var form = jQuery(this).parents('form:first');
var title = jQuery("input[name='process']", form).val();
$('#tt').tabs('add',{
title:title,
content:'Script starting',
closable:true
});
$('div.panel-body:last').attr("id","tab" + panelIds[panelIds.length - 1] + 1);
panelIds.push(panelIds[panelIds.length - 1] + 1);
//var j = jQuery.noConflict();
var fileName = jQuery("input[name='process']", form).val();
var XHR;
var stopMe = 1;
var isSame = 0;
var oldhtml;
var tabID = "tab" + panelIds[panelIds.length - 1];
//alert(tabID);
jQuery("#"+ tabID).everyTime(1000, function (i) {
//alert(stopMe);
//add also if stopme=false else quit/end/whatever
if (stopMe != 2){
//alert(stopMe);
XHR = jQuery.ajax({
url: "/eemcontrolpanel/jobs/" + fileName + ".txt",
cache: false,
success: function (html){
//alert(html);
if (html === oldhtml){
isSame++;
//alert(isSame);
if (isSame === 10){
stopMe = 2;
//alert(stopMe);
}
}
jQuery("#"+ tabID).html("<pre>" + html + "</pre>").scrollHeight;
oldhtml = html;
//alert(oldhtml);
}
});
} else {
jQuery("#"+ tabID).stopTime();
}
jQuery("#"+ tabID).css({ color: "white" });
});
} else {
return false;
}
});
Have you tried this:
Function onButtonPush(){
if(confirm('confirm message')){
function1();
function2();
function3();
}
}

Progress bar while uploading large files with XMLHttpRequest

I am trying to upload some large files to the server using XMLHttpRequest and file.slice.
I've manage doing this with the help of documentations and other various links.
Since uploading large file is a lengthily job, i would like to provide the user with a progress bar.
After some more readings i've come across on an example that, theoretically, does exactly what i need.
By taking the sample code and adapting it to my needs i reached
var upload =
{
blobs: [],
pageName: '',
bytesPerChunk: 20 * 1024 * 1024,
currentChunk: 0,
loaded: 0,
total: 0,
file: null,
fileName: "",
uploadChunk: function (blob, fileName, fileType) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.responseText) {
// alert(xhr.responseText);
}
}
};
xhr.addEventListener("load", function (evt) {
$("#dvProgressPrcent").html("100%");
$get('dvProgress').style.width = '100%';
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var progress = Math.ceil(((upload.loaded + evt.loaded) / upload.total) * 100);
$("#dvProgressPrcent").html(progress + "%");
$get('dvProgress').style.width = progress + '%';
}
}, false);
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var progress = Math.ceil(((upload.loaded + evt.loaded) / upload.total) * 100);
$("#dvProgressPrcent").html(progress + "%");
$get('dvProgress').style.width = progress + '%';
}
}, false);
xhr.open('POST', upload.pageName, false);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", fileName);
xhr.setRequestHeader("X-File-Type", fileType);
xhr.send(blob);
},
upload: function (file) {
var start = 0;
var end = 0;
var size = file.size;
var date = new Date();
upload.fileName = date.format("dd.MM.yyyy_HH.mm.ss") + "_" + file.name;
upload.loaded = 0;
upload.total = file.size;
while (start < size) {
end = start + upload.bytesPerChunk;
if (end > size) {
end = size;
}
var blob = file.slice(start, end);
upload.uploadChunk(blob, upload.fileName, file.type);
start = end;
upload.loaded += start;
}
return upload.fileName;
}
};
The call is like (without the validations)
upload.upload(document.getElementById("#upload").files[0]);
My problem is that the progress event doesn't trigger.
I've tried xhr.addEventListener and with xhr.upload.addEventListener (each at a time and both at a time) for the progress event but it never triggers. The onreadystatechange and load events trigger just fine.
I would greatly appreciate help with what i am doing wrong
Update
After many attempts i've manage to simulate a progress but i've ran into another problem: Chrome's UI is not updating during the upload.
The code looks like this now
var upload =
{
pageName: '',
bytesPerChunk: 20 * 1024 * 1024,
loaded: 0,
total: 0,
file: null,
fileName: "",
uploadFile: function () {
var size = upload.file.size;
if (upload.loaded > size) return;
var end = upload.loaded + upload.bytesPerChunk;
if (end > size) { end = size; }
var blob = upload.file.slice(upload.loaded, end);
var xhr = new XMLHttpRequest();
xhr.open('POST', upload.pageName, false);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", upload.fileName);
xhr.setRequestHeader("X-File-Type", upload.file.type);
xhr.send(blob);
upload.loaded += upload.bytesPerChunk;
setTimeout(upload.updateProgress, 100);
setTimeout(upload.uploadFile, 100);
},
upload: function (file) {
upload.file = file;
var date = new Date();
upload.fileName = date.format("dd.MM.yyyy_HH.mm.ss") + "_" + file.name;
upload.loaded = 0;
upload.total = file.size;
setTimeout(upload.uploadFile, 100);
return upload.fileName;
},
updateProgress: function () {
var progress = Math.ceil(((upload.loaded) / upload.total) * 100);
if (progress > 100) progress = 100;
$("#dvProgressPrcent").html(progress + "%");
$get('dvProgress').style.width = progress + '%';
}
};
Update 2
I've managed to fix it and simulate a progress bar that works in chrome too.
i've updated previous code sample with the one that works.
You can make the bar 'refresh' more often by reducing the size of the chunk uploaded at a time
Tahnk you for your help
As stated in https://stackoverflow.com/a/3694435/460368, you could do :
if(xhr.upload)
xhr.upload.onprogress=upload.updateProgress;
and
updateProgress: function updateProgress(evt)
{
if (evt.lengthComputable) {
var progress = Math.ceil(((upload.loaded + evt.loaded) / upload.total) * 100);
$("#dvProgressPrcent").html(progress + "%");
$get('dvProgress').style.width = progress + '%';
}
}
There is my solution:
function addImages(id) {
var files = $("#files").prop("files");
var file = files[loopGallery];
var cList = files.length;
var fd = new FormData();
fd.append("file", file);
fd.append("galerie", id);
var xhr = new XMLHttpRequest();
xhr.open("POST", "moduls/galerie/uploadimages.php", true);
xhr.upload.onprogress = function(e) {
var percentComplete = Math.ceil((e.loaded / e.total) * 100);
$("#progress").css("display","");
$("#progressText").text((loopGallery+1)+" z "+cList);
$("#progressBar").css("width",percentComplete+"%");
};
xhr.onload = function() {
if(this.status == 200) {
$("#progressObsah").load("moduls/galerie/showimages.php?ids="+id);
if((loopGallery+1) == cList) {
loopGallery = 0;
} else {
$("#progressBar").css("width", "0%");
loopGallery++;
addImages(id);
}
}
}
if(cList > 0) {
xhr.send(fd);
}
}

XMLHttpRequest don't send to another page

I use this code to upload files, and this code have a progressbar. The problem with this code is that it never send me to "upload.php" after it have uploaded the file, after it reach 100% on the progressbar. (It's not my code).
The code:
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
The whole script
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
var uploadingcanceld = "حدث خطأ أثناء تحميل الملف";
function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600))/60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {hr = "0" + hr; }
if (min < 10) {min = "0" + min;}
if (sec < 10) {sec = "0" + sec;}
if (hr) {hr = "00";}
return hr + ':' + min + ':' + sec;
};
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
function fileSelected() {
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('ufile').files[0];
// filter for image files
var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! rFilter.test(oFile.type)) {
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e){
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // binding onload event
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
function startUploading() {
// cleanup all temp states
iPreviousBytesLoaded = 0;
$("#upload").animate({height:'75px'},350);
$("#loadingborders").fadeIn(1500);
$("#progress_percent").fadeIn(1500);
$("#upload_button").fadeOut(100);
$("#ufile").fadeOut(100);
document.getElementById('ufile').style.margin = '5px 0px -5px 0px';
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
document.getElementById('progress_percent').innerHTML = '';
var oProgress = document.getElementById('progress');
oProgress.style.display = 'block';
oProgress.style.width = '0px';
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
// set inner timer
oTimer = setInterval(doInnerUpdates, 300);
}
function doInnerUpdates() { // we will use this function to display upload speed
var iCB = iBytesUploaded;
var iDiff = iCB - iPreviousBytesLoaded;
// if nothing new loaded - exit
if (iDiff == 0)
return;
iPreviousBytesLoaded = iCB;
iDiff = iDiff * 2;
var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
var secondsRemaining = iBytesRem / iDiff;
// update speed info
var iSpeed = iDiff.toString() + 'B/s';
if (iDiff > 1024 * 1024) {
iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
} else if (iDiff > 1024) {
iSpeed = (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
}
document.getElementById('speed').innerHTML = iSpeed;
document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}
function uploadProgress(e) { // upload process in progress
if (e.lengthComputable) {
iBytesUploaded = e.loaded;
iBytesTotal = e.total;
var iPercentComplete = Math.round(e.loaded * 100 / e.total);
var iBytesTransfered = bytesToSize(iBytesUploaded);
document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
document.getElementById('b_transfered').innerHTML = iBytesTransfered;
if (iPercentComplete == 100) {
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = '<h1>Please wait...processing</h1>';
}
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadFinish(e) { // upload successfully finished
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = e.target.responseText;
document.getElementById('progress_percent').innerHTML = '100%';
document.getElementById('progress').style.width = '400px';
document.getElementById('filesize').innerHTML = sResultFileSize;
document.getElementById('remaining').innerHTML = '| 00:00:00';
clearInterval(oTimer);
}
function uploadError(e) { // upload error
$('#errormessage').slideUp('fast', function() {
$('#errormessage').html(uploadingcanceld);
$('#errormessage').slideDown('fast');
});
clearInterval(oTimer);
}
function uploadAbort(e) { // upload abort
clearInterval(oTimer);
}
XHR is a dynamic data call, it's not a document forwarding call, meaning the reason why we have XHR to begin with is so that we DON'T want to forward a client to another page to get new content into the page. So you might want to wait on the XHR to complete the process of sending the data, acquire the results of that transfer via XHR, and based on those results do as you want.
So in essence, you are creating a virtual document client/server transfer and handshake without having to forward the client, that of which is the role XHR was created to fulfill.

Categories