Detect bad vimeo url with Jquery and Ajax - javascript

I'm experimenting with a site that generates random vimeo urls and plays them full screen with javascript. The site has a vhs appearance and is navigated with the arrow keys. (up arrow to "play" a vid, down to "pause").
VHS
I have the player working but am having difficulty detecting 404 and permission errors. I'm using ajax, json, and referenced this helpful thread. This thread as well.
Currently, I get my "Bad ID" alert when a valid url is generated and nothing when a bad url is generated. I would ideally like to re-generate video IDs until successful so users would never see a 404 or be asked for a password. Here is the meat of my code:
// if up arrow is pushed, show play div and hide others
if(e.which == 38) {
//generate video id and url
var video_id = Math.floor((Math.random()*10000000)+1)
var url ="https://vimeo.com/" + video_id;
var video_json = 'http://vimeo.com/api/v2/video/' + video_id + '.json';
//detect 404 with ajax
$.ajax({
type: 'GET',
url: video_json,
data: {format: 'jsonp'},
dataType: 'jsonp',
crossDomain: true,
success: function(resp) {
if (resp["id"]) {
alert ('good ID');
}
else {
alert ('bad ID');
//re-generate video_id until good
}
},
});
console.log(url);
console.log(video_json);
//play video with okvideo
$(function(){
$.okvideo({ source: url,
volume: 100,
loop: true,
hd:true,
adproof: true,
annotations: false,
// disablekeyControl: true,
onFinished: function() { console.log('finished') },
unstarted: function() { console.log('unstarted') },
onReady: function() { console.log('onready') },
onPlay: function() { console.log('onplay') },
onPause: function() { console.log('pause') },
buffering: function() { console.log('buffering') },
cued: function() { console.log('cued') },
});
});
Does anyone have suggestions? I understand this is a kind of hacky way to do accomplish this; there are obviously same-origin barriers at play and I'm open to using the API if this is method is a dead-end.
Thanks in advance!

Related

JavaScript - Multiple Overlapping Async GET Requests?

I have tried ways to search for a solution but I can't seem to find the right combination of words or something... here goes:
I have an ASP.NET MVC application that users scan inventory/package barcodes into. Every time someone scans an item, I make an async request and then display a popup message with information about the package. This part works as expected and does not block the application during the request:
$.ajax({
type: 'GET',
dataType: 'json',
async: false,
url: '#Url.Action("SingleOrderLookup")?trackingNumber=' + trackingId,
success: function (result) {
if (result.success) {
var audio = findAudio(result.model, audioClips, saturdayAudio);
suppressDefaultSound = true;
var titleText = result.model.displayPromptText;
if (result.model.isRefrigerated) {
isRefrigerated = true;
titleText = "<p style='color: blue;'>(REFRIGERATED)</p>" + "<p>" + result.model.displayPromptText + "</p>";
}
swal.fire({
title: titleText,
text: "Place in route for " + result.model.displayPromptText,
type: "success",
showCancelButton: false,
confirmButtonText: "Sorted",
cancelButtonText: "Cancel",
timer: 1750,
preConfirm: function () {
return new Promise(function (resolve) {
resolve();
}, 1000);
}
}).then(result => {
if (result.value) {
}
});
var dupe = findOrderByTrackingNumber(trkNumbers, result.model.trackingId);
if (!dupe) {
trkNumbers.push({ trackingNumber: trackingId, depotId: result.model.destinationHub });
pkgCount++;
if ($("#divUpdatePickup").is(":hidden"))
$("#divUpdatePickup").show();
AddLogToTable(trackingId);
} else {
//audible feedback that duplicate was scanned
//if (!trkBin) PlayAudio(2);
//PlayAudio(2);
}
//playing audio
if (isRefrigerated) {
setTimeout(function () {
if (audio) playByteArray(audio);
}, 1500);
PlayRefrigerate();
} else {
if (audio) playByteArray(audio);
}
}
if (result.nullRoute) {
addToTrkNumbers = false;
Swal.fire({
title: "NO ROUTE DEFINED",
text: "Unable to match order to a route!",
type: "warning",
showCancelButton: false
});
}
}
});
However, I want the page to make another async call to populate a variable with an array of objects, transparently and without blocking the user from making scans and receiving information back from the async calls from the above code. This call should occur immediately when the page is loaded, and it could take more than a minute or two to receive all the data expected from this call. Once the response is back, the collection variable (zipSort[]) should be populated. The data in this variable will contain a "cache" of elements that the page can query against to avoid having to make individual server-side calls after each scan (in essence, I want to "front-load" data needed for the scan events and once completed, individual calls to the server should not be necessary since this variable should contain 99% of the IDs expected to be scanned).
This is where I'm having an issue and it's probably due to a lack of understanding of how async calls/JS promises work. Here is the code I have so far for this:
//array to hold data on expected tracking number scans
var zipSort = []
async function getCheckinGroup(zipSort) {
console.log("Fetching complete check-in group...");
var url = '/SortFacility/HubManager/GetOrders';
var promise = new Promise((resolve,reject) => {
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
if (result.success) {
console.log("Retrieval success");
try {
zipSort = result.model;
resolve(result.model);
} catch (ex) {
reject("Some error?");
}
} else {
reject("Some error?");
}
},
error: function (ob, errStr) {
reject("Something went wrong");
}
});
});
return promise;
}
//don't want this to hold up execution of the rest of the code, so zipSort[] should
//remain empty and get set transparently when the ajax response is returned:
getCheckinGroup(zipSort);
Every version of code I'm trying out from articles and tutorials I have read holds up the UI and keeps users from being able to scan items while the response hasn't been returned. What am I missing? How should I change this so that (a) users can begin scanning immediately once the page has loaded and receive information from individual async calls to the DB, and (b) zipSort[] can be populated with the totality of any data potentially needed for these scans, and once populated, scan events trigger a lookup on that variable instead of continued individual calls to the database?
Any help would be appreciated!
Edit: tried simply adding this call in-line and no matter where I put it, it blocks the other code from running until response is received, even though async is set to true:
$.ajax({
type: "GET",
url: url,
cache: false,
async: true,
contentType: "application/json",
success: function (result) {
console.log("Data received.");
zipSort = result.model;
}
});
Thanks everyone for your help. I found this little gem, which solved my problem:
https://josef.codes/c-sharp-mvc-concurrent-ajax-calls-blocks-server/
Applying [SessionState(System.Web.SessionState.SessionStateBehavior.Disabled)] to my controller class enabled concurrent async ajax calls.

Slow upload speed with Ajax call

I have an interesting problem - I have my own IIS 2016 server, that I use to host a website which allows the users to upload a variety of files - some in text format, the others zip'ed up together. Initially the website would return error 500 from the server when trying to upload something bigger, like ~50MB. I Googled up that IIS requires configuration of maxAllowedContentLength (changed default to 209715200, ~300MB) and FastCGI's parameters for IDLE, ACTIVITY and REQUEST (changed to 600) in order to allow bigger files upload without hitting the file size limit. However, now that the files are getting uploaded, the upload speed for these bigger files slowed down to a crawl. Previously I could upload ~20MB files in 10sec on a local network, while now 50MB takes like ~160sec. Not a linear increase I would expect.
My website runs on Django, and my POST method file transfer is carried out by Ajax call in JS:
$('#sn').on('submit', function(event) {
event.preventDefault();
var post_data = new FormData($("#sn")[0]);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
var percent = Math.round(evt.loaded/evt.total * 100)
console.log(percent)
$('#query_button').attr('disabled', true)
$('#query_button').get(0).innerText = "Upload status: " + percent + '%'
}, false);
xhr.upload.addEventListener("load", function(evt) {
$('#query_button').get(0).innerText = "PLEASE WAIT..."
}, false);
return xhr;
},
url: '#',
type: "POST",
data: post_data,
processData: false,
contentType: false,
dataType: "json",
statusCode: {
200: function() {
// alert("Server received request and posted a response!");
},
404: function() {
alert("Error code 404: Page not found!");
},
408: function() {
alert("Error code 408: Request Timeout!");
},
500: function() {
alert("Error code 500: Internal server error!");
}
},
success: function(response) {
console.log(response)
}
});
})
Can anybody please tell me, if the Ajax call could be the culprit of this slow-down in upload speed, or if it is something else that needs to be adjusted on IIS?

AJAX request not executing inside chrome alarm

I am fairly new to AJAX and recently I've implemented chrome alarm in my background script. Here is my background.js :
chrome.alarms.onAlarm.addListener(function(alarm) {
alert("Begin");
$.ajax({
type: "GET",
url: "myURLhere",
datatype : 'jsonp',
crossDomain: true,
success: function(res)
{
alert('Success1');
},
error: function() {
alert("Error occurs!");
}
});
alert("We're done");})
So the problem is that, without the alarm my ajax request was executing successfully but now its never going into the success part. I always get 3 alerts (Begin,Error occurs! and We're done) and I have been wondering why since past few days.
Here is my popup.js file where the alarms are being set.
var alarmClock = {
onHandler : function(e) {
chrome.alarms.create("myAlarm", {delayInMinutes: 0, periodInMinutes: 2} );
window.close();
},
offHandler : function(e) {
chrome.alarms.clear("myAlarm");
window.close();
},
setup: function() {
var a = document.getElementById('alarmOn');
a.addEventListener('click', alarmClock.onHandler );
var a = document.getElementById('alarmOff');
a.addEventListener('click', alarmClock.offHandler );
}}; document.addEventListener('DOMContentLoaded', function () { alarmClock.setup(); });
Thanks in advance :)

Ajax form in qTip2

I have a table with a list of names, their attributes and comments for each record. I want to be able to display the comments in a tooltip, and also be able to update those comments via Ajax. I would like to show a tooltip or a modal by clicking on a link. This modal will have a textarea with the comments preloaded. The user can modify the comments and submit them to the action page via Ajax. On successful submission the existing tooltip content will also need to be updated.
Any help would be greatly appreciated.
I am using the qtip2 and tipsy plugins.
I am loading the form in the qTip2 tooltip, onclick, through ajax. The link to the form is brought over from the rel tag. Now when I submit the form, it doesn't submit through ajax but directly the action page. This is my JS code:
$('.commentsedit').each(function()
{
// We make use of the .each() loop to gain access to each element via the "this" keyword...
$(this).qtip(
{
content: {
// Set the text to an image HTML string with the correct src URL to the loading image you want to use
text: '<img class="throbber" src="images/throbber.gif" alt="Loading..." />',
ajax: {
url: $(this).attr('rel') // Use the rel attribute of each element for the url to load
},
title: {
text: $(this).attr('title'), // Give the tooltip a title using each elements text
button: true
}
},
position: {
at: 'bottom center', // Position the tooltip above the link
my: 'top right',
viewport: $(window), // Keep the tooltip on-screen at all times
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true // Only show one tooltip at a time
},
hide: 'unfocus',
style: {
classes: 'my_width_setting_class qtip-wiki qtip-light qtip-shadow'
},
events: {
render: function(event, api) {
// Capture the form submission
$('form', this).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':textarea', this);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: 'commentsform.cfm',
data: $(this).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', data.message + ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
});
}
}
})
})
Although an old question, I think that someone will find useful the solution proposed to a similar problem in the qtip2 developer's site and specifically in
http://craigsworks.com/projects/forums/showthread.php?tid=3680
Edit: in response to a comment I reproduce the main part of the answer as a reference:
$('a[class=qTipForm][rel]').each(function(){
var formName = $(this).attr('name');
$(this).qtip({
content: {
//text: '<iframe src="'+$(this).attr('rel')+'" height="400px" width="700px" frameborder="0"></iframe>',
text: 'Loading...',
ajax: {
url: $(this).attr('rel'),
success: function(data) {
// Set the tooltip contents
this.set('content.text', data);
// Bind the form submit event
$('#' + formName).bind('submit', function(event) {
// Grab and store input elements
var inputs = $(':input','#' + formName);
// Common ajax error handler
function errorHandler(jqXHR, message) {
// Set the error and show/hide it
$('.error', api.elements.tooltip).html(message || '').toggle(!!message);
}
// Setup AJAX request
$.ajax({
url: $('#' + formName).attr('action'),
data: $('#' + formName).serialize(),
type: 'post',
dataType: 'json',
success: function(data, status, jqXHR) {
// On success, show message and refresh after 2 seconds
if(data.status === 'success'){
api.set('content.text', ' Redirecting...');
setTimeout(function(){ window.location.reload() }, 2000);
}
// Call error handler on error status too.
else { errorHandler(jqXHR, data.message); }
},
error: errorHandler,
// Disable/Enable input elements
beforeSend: function() { inputs.attr('disabled', 'disabled'); },
complete: function() { inputs.removeAttr('disabled'); inputs[0].focus(); }
});
// Prevent normal form submission
event.preventDefault();
})
}
},
title: {
text: $(this).attr('title'),
button: true
}
},
position: {
my: 'center',
at: 'center', // Position the tooltip above the link
target:$(window),
effect: false // Disable positioning animation
},
show: {
event: 'click',
solo: true, // Only show one tooltip at a time
modal: true
},
hide: false,
style: {
classes: 'viewTipForm ui-tooltip-rounded ui-tooltip-light',
tip: false
}
})
.click(function(event) { event.preventDefault(); });
})

Open ajax jstree results in popup window

Ok, so I spent a lot of time getting jstree to open in a dialog box upon a successful ajax call. Now they want a popup window instead. Seems like it should be easy, but my window gives a 404 error. I'm using Grails, btw. Here's the current code (re-typing, so forgive any syntax errors):
$.ajax({
type: 'POST',
url: 'resultsView/viewAsdf'
traditional: true,
data: {
documentID: contentID
},
success: function (data) {
var data1 = {'data':data}
var $genericDialog = $("#genericDialog");
$genericDialog.jstree({
"html_data": data1
[snip]
}),
$genericDialog.dialog({
title: "ASDF"
modal: true,
height: 700,
width: 450,
buttons: {
"OK": function() {$genericDialog.dialog("close");}
}
});
}
});
So now my question is how do I substitute a window for what's currently the dialog box? What would the url of the window be, since I've already called the url in the ajax method?

Categories