Executing an AJAX call within another AJAX call (no jQUERY) - javascript

I am using a third party API to upload a video to that server. Once I have uploaded the video I make a verification call to check if all the file has been uploaded ('verifyUpload()'). If all the file has been uploaded then great, otherwise I resume the upload ('resumeUpload()') from the last byte that was uploaded. The problem that i am having, and I do not understand why, is that my 'resumeUpload()' does not appear to be executing - have i coded this incorrectly?
In the console I can see the following lines executing from resumeUpload():
console.log('vim.resumeUpload() ...');
console.log('stringArgument: ' + stringArgument);
But instead of the line:
xmh.setRequestHeader('Content-Range', stringArgument);
being executed I am seeing :
xmh.setRequestHeader('Content-Range', 'bytes /');
being executed from verifyUpload().
verifyUpload()
// VERIFY UPLOAD (SO FAR)
var verifyUpload = function(){
console.log('verifying upload() ...');
var xmh = new XMLHttpRequest;
xmh.onreadystatechange = function(){
console.log('xmh.readyState111: ' + xmh.readyState);
console.log('xmh.status111: ' + xmh.status);
if(xmh.readyState == xmh.HEADERS_RECEIVED){
console.log('VERIFY RESPONSE HEADERS: ' + xmh.getAllResponseHeaders());
console.log('getResponseHeader(\'Content-Range\')' + xmh.getResponseHeader("Range"));
var range = xmh.getResponseHeader("Range");
var rangeArray = range.split('-');
var bytesUploaded = rangeArray[1];
bytesUploaded = Number(bytesUploaded);
var leftToUpload = vim.vidFileSize-bytesUploaded;
console.log('bytesUploaded: '+bytesUploaded);
console.log('byteLeftToUpload: '+ leftToUpload);
// IF ALL THE FILE HAS BEEN UPLOADED TO THE SERVER
// COMPLETE UPLOAD
if(leftToUpload == 0){
completeVidUpload();
}else{
// NEED TO RESUME UPLOAD FROM WHERE WE LAST LEFT OFF
vim.bytesToUploadFrom = bytesUploaded + 1;
var stringValue = 'bytes '+vim.bytesToUploadFrom+'-'+vim.vidFileSize+'/'+vim.vidFileSize+'';
console.log('stringValue: '+ stringValue);
resumeUpload(stringValue);
}
}
}
xmh.open('PUT', vim.upload_link_secure);
xmh.setRequestHeader('Content-Range', 'bytes */*');
xmh.send();
}
resumeUpload():
// RESUME UPLOAD WHERE LEFT OFF
var resumeUpload = function(stringArgument){
console.log('vim.resumeUpload() ...');
console.log('stringArgument: ' + stringArgument);
var xmh = XMLHttpRequest;
// SET EVENT LISTENERS
// SET EVENT LISTENERS
xmh.upload.addEventListener('progress', uploadProgres, false);
xmh.addEventListener('load', uploadComplete, false);
xmh.addEventListener('error',uploadError, false);
xmh.onreadystatechange = function(){
if(xmh.readyState == xmh.HEADERS_RECEIVED){
console.log('VERIFY RESPONSE HEADERS222: ' + xmh.getAllResponseHeaders());
console.log('getResponseHeader(\'Content-Range\')222' + xmh.getResponseHeader("Range"));
}
}
xmh.open('PUT', vim.upload_link_secure);
xmh.setRequestHeader('Content-Range', stringArgument);
xmh.send();
}

I think you missed new in resumeUpload here:
var xmh = XMLHttpRequest;

Related

My script which was working quit. I am trying to upload an image from my phone and this has stopped working

My tale of woe continues, trying to make an app that will allow me to upload pix from my mobile device. I can do an "after the fact" separate 'page' that will work and add a photo, but I want it all inclusive. THIS WAS WORKING AND IT JUST QUIT ON ME. I don't know if I'm going to have much hair left.
My image form tag looks like this:
Photo: <input type="file\ name="fileToUpload" id=\fileToUpload" onchange="fileSelected();" accept="image/*" />
Here it the portion of the javascript that is somehow breaking. I alerted it to see if the string looks right and it does. The end of it is sending values to the php script that completes the upload and adds data to my database table. (All of that is working). ALSO - this works FINE from a desktop:
function uploadFile() {
var fd = new FormData();
var count = document.getElementById('fileToUpload').files.length;
for (var index = 0; index < count; index ++)
{
var file = document.getElementById('fileToUpload').files[index];
fd.append('myFile', file);
}
var itemName = document.getElementById('ItemName').value;
var mccats = document.getElementById('mccats').value;
var sccats = document.getElementById('sccats').value;
var description = document.getElementById('description').value;
var notes = document.getElementById('notes').value;
var location = document.getElementById('location').value;
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "additem.php?action=newitem&item=" + itemName + "&mccats=" + mccats + "&sccats=" + sccats + "&description=" + description + "&notes=" + notes + "&location=" + location);
xhr.send(fd);
}
I get that there was an error trying to upload my file even though my progress bar shows that it went - 100%. Then I get the error saying it's bad.

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

Passing generated id from one page to another

I really really need your help pls. I have been battling with these for days and my project is stucked. Your help will really be appreciated.
I have 3 pages.
Page one receives my data, and html formatted version is created. it is a loop and it returns 10 posts.
===
page 2 is the html page that displays the 10 post
====
page 3. the posts at page 2 are just featured image and excerpt and title with url... to read full, click it and go to page 3 ...
Page 3 uses the unique id of each posts to display the full post:
my question: how do i pass each post id to page 3 for full content view.
i tried to store the id generated in page 1 to localstorage, but bcos its a loop ... ONLY THE LAST ONE IS STORED..
my code..
Page 1 - script page receives data
document.addEventListener("deviceready", onDeviceReady, false);
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts?_embed');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
createHTML(data);
console.log(data);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
Page 1 still: CreateHTMl create thru a loop
function createHTML(postsData) {
var ourHTMLString = '';
for (i = 0; i < 1; i++)
{
var posturl = postsData.link
ourHTMLString +='<tr>';
ourHTMLString += '<td>' + '' + postsData[i].title.rendered + ''+'</td>';
ourHTMLString += '<td>' + '<img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '" />' + ''+'</td>';
ourHTMLString += '<td>' + postsData[i].excerpt.rendered + localStorage.setItem("postid",postsData[i].id)+'</td>';
//i tried to store each id in a localstorage but only the last one remains
ourHTMLString+= '</tr>';
} portfolioPostsContainer.innerHTML = ourHTMLString;
}
page two uses this to display ourHTMLString
<div id="portfolio-posts-container"></div>
page 3 Need each post id.
function onDeviceReady(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://myurl/wp-json/wp/v2/posts/'+mypostid+'?_embed=true')
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var data = JSON.parse(ourRequest.responseText);
// createHTML(data); '+mypostid)
console.log(data);
var ourHTMLString = '';
Each post has its generated id from the api, how do i pass it to page 3 for displaying individual post
Although I'm a little confused as re the overall structure of this system, you could pass the id as a query string parameter.
View post 123
This can be parsed using location.search within JavaScript:
var postMatch = /id=(\d+)/.exec(location.search);
if(postMatch) {
var postId = postMatch[1];
// Load post postId...
} else {
// No post was passed
}

php get video from file_get_contents('php://input')

I'm trying to upload a video with some other parameters via a shared web worker.
Here below I paste de code I'm using:
record.js
function sendVideo(name, path) {
var worker = new SharedWorker("js/upload.js");
worker.port.postMessage([path, name + '.webm', blob]);
// worker.port.start();
worker.port.onmessage = function(e) {
console.log('Message received from worker ' + e.data);
}
}
upload.js
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
var path = e.data[0];
var fileName = e.data[1];
var video = e.data[2];
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/channel/upload', true);
request.onload = function () {
port.postMessage(request.responseText);
};
request.send('fileName=' + fileName + '&video=' + video);
}
// port.start(); // not necessary since onmessage event handler is being used
}
channel.php
public function upload()
{
$data = file_get_contents('php://input');
// get the video from $data and move it
}
The problem is if my worker send:
request.send('fileName=' + fileName + '&video=' + video);
the content that my php code get is [blob data].
and if my worker send:
request.send('video=' + video);
the content that my php get is the video coded, full of special characters.
My question is how could I get the text and the video like if I had $_FILES in order to process it correctly.
Thanks in advice.

Load a JavaScript event the last in CRM form

I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.

Categories