How can I wait for XHR? - google-chrome

I want to wait for the XHR to open after I continue with the program but synchronous XHR is deprecated in chrome api. How can I get around this?

Using a callback to continue execution seems like the best method. Without a clear example of your project here's a generalized option:
function performRequest() {
// ... Some code
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bar/foo.txt", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
useRequest(xhr.responseText);
}
};
}
function useRequest(data) {
// Continue with your application
}
performRequest();

Related

Web application for recording video from user's web camera

I am interested in building a web application, which will be served by nginx, and that will ask user access to their web camera, record for a given time period, maybe replay it to user, and store it in the server.
I am also thinking of a basic user interface. Could that be pure HTML+PHP?. Could that be python?
Similar questions here do not seem very relevant/helpful.
What would you suggest?
You can use MediaRecorder to record video from webcam.
Record a video and save its data to recordedBlobs:
function handleDataAvailable(event) {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
}
function startRecording() {
recordedBlobs = [];
let options = { mimeType: 'video/webm;codecs=vp8' };
let types = ['video/webm;codecs=vp9', 'video/webm\;codecs=h264', 'video/webm', 'video/mpeg', ''];
for (let i in types) {
try {
if (MediaRecorder.isTypeSupported(types[i])) {
options = { mimeType: types[i] };
break;
}
}
catch (e) {
console.log('Exception while creating MediaRecorder: ${JSON.stringify(e)}');
}
}
try {
mediaRecorder = new MediaRecorder(window.stream, options);
} catch (e) {
console.error('Exception while creating MediaRecorder: ${JSON.stringify(e)}');
return;
}
mediaRecorder.onstop = (event) => {
console.log('Recorder stopped: ', event);
};
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10); // collect 10ms of data
}
function stopRecording() {
mediaRecorder.stop();
}
Upload the video data to your action page:
function upload() {
const blob = new Blob(recordedBlobs, { type: 'video/webm' });
var formData = new FormData();
formData.append("video", blob, fileName + ".webm");
var xhr = new XMLHttpRequest();
xhr.open("POST", "upload.aspx");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
}
}
};
xhr.onerror = function () {
alert(`Network Error`);
};
xhr.send(formData);
}
You can implement the action page in any programming language, PHP, Java, Python, or C#.
No. Access to the user's webcam through a browser requires JavaScript and APIs provided to it by the browser.
Serverside programs do not run on the user's computer and thus cannot access its hardware (and Python and PHP cannot run client-side from a webpage).

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

API errors on Google Apps Script

I created a POST function to Harvest using postman and it was successful, I exported the code in as javascript but then when I go to run it in the google apps script I get, ‘ReferenceError: “FormData” is not defined.’
Any idea what this is referring too?
function myFunction() {
var data = new FormData();
data.append(“name”, “TEST_CLIENT”);
data.append(“is_active”, “true”);
data.append(“address”, “”);
data.append(“currency”, “USD”);
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener(“readystatechange”, function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open(“POST”, “https://api.harvestapp.com/v2/clients?
name=TEST_CLIENT&is_active=true&address=1%20Main%20st.%20&currency=USD”);
xhr.setRequestHeader(“Authorization”, “Bearer {{$ACCESS_TOKEN}}”);
xhr.setRequestHeader(“Harvest-Account-Id”, “{{$ACCOUNT_ID}}”);
xhr.setRequestHeader(“User-Agent”, “(hidden)”);
xhr.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded”);
xhr.setRequestHeader(“Cache-Control”, “no-cache”);
xhr.setRequestHeader(“Postman-Token”, “HIDDEN”);
xhr.send(data);
}
I hid some parts of my code

JSONP callback issue

I'm trying to get JSONP working with a server running on an Arduino.
This is my JS code:
window.onload = init;
function init()
{
//alert("Test");
SendRequest();
}
function SendRequest()
{
alert("Sending request");
var url = "http://192.168.1.177";
var request = new XMLHttpRequest();
request.open("GET", url);
request.error = function(e) {
alert("ERROR");
};
request.send(null);
}
function ArduinoJSONP()
{
alert("Callback received!!!");
}
The callback function is never reached.
But if I just direct my browser directly to the Arduino IP I see the following displayed in the browser:
ArduinoJSONP({"data": 12345})
So it seems the server is sending the response with correct JSONP format but somehow the function is not invoked. Is there anything else I need to for JS to call the function? I even tried moving the function to the HTML body but it didn't help either.
Thank you.
You are not handling server response at all. If you doing it without any libraries you need to eval result that was returned by the server.
And actually JSONP implementation is not XHR, you have to inject it as a script tag into html with correct src attribute.
Just use a library that already have all this logic abstracted for you.
Simply inject script tag into HTML tree:
function SendRequest()
{
var element = document.createElement('script');
var s = document.getElementsByTagName('script')[0];
element.type = 'text/javascript';
element.async = true;
element.src = 'http://192.168.1.177';
s.parentNode.insertBefore(element, s);
}
You can mark it with unique id. Hookup to onload event and once executed remove that script.

Javascript array for AJAX POST send

Here is the deal... I need to make an AJAX save script. I have a whole system built on php and every action needs a refresh... I'm trying to minimize the refresh count by using AJAX ... I can't seem to find a way how to send a WYSIWYG editor output without loss to the PHP script...
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
function save(){
xmlhttp.open('POST','action.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", document.getElementById('output').value.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(document.getElementById('output').value);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status==200){
$('#ajaxresult').css('opacity', 0.1);
$('#ajaxresult').stopAll().pause(1000).fadeTo(400,1);
$('#ajaxresult').stopAll().pause(3000).fadeTo(400,0, function(){$(this).hide();});
document.getElementById('ajaxresult').innerHTML=xmlhttp.responseText;
}
}
}
While this script works fine I can't seem to find the way what kind of array to give the send option... what is the syntax or is there something I don't know?
BTW I'm a beginner in JS...
I'd look into using jQuery and it's Ajax library:
http://api.jquery.com/jQuery.ajax/
Instead of doing all that you'd simply do:
$.post({url: 'action.php',data: output,success: function() { /* do something here */ }});
create custom parameter in the javascript code like below:
var jspNameParam = "content="+escape(document.getElementById('output').value);
function myFunction() {
if (xmlhttp) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
/* want to accsess some data written from action.php */
}
};
xmlhttp.open("POST", "action.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send(jspNameParam);
}
}
Now in action.php you will get whole content with the parameter name content.