How do I pass a variable to into HttpRequest? - javascript

I want to give the request.onload function a variable, and add the request.response into that variable. How do I do that?
function loadathing(url, target){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function() {
target = request.response;
};
}
This doesn't work because it forgets what target is.

You have two problems here. First, in order to pass the response to target, you would need to do it on a property of target rather than target directly since target can't be a native value (native values such as strings and numbers cannot be passed by reference).
function loadathing(url, target){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function() {
target.response = request.response;
};
}
var target = {};
loadathing('foo.php', target);
Secondly, since you are performing an asynchronous ajax request, you will need to add a callback to your function so that the outer code knows when target.response is populated.
function loadathing(url, target, cb){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function() {
target.response = request.response;
cb();
};
}
var target = {};
loadathing('foo.php', target, function () {
console.log(target.response);
});
You can then simplify it by removing target all together and using the callback.
function loadathing(url, cb){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onload = function() {
cb(request.response);
};
}
loadathing('foo.php', function (response) {
console.log(response);
});

Related

Passing JavaScript object to another function

I'm using an API that allows me to access JSON objects which I've used and convert in to a JavaScript object. I get a console log of film names so this works.
Now I'm I was wondering is it possible to reference this film object in other functions? or do I need to do a request in every function to access the film properties?
$("#search-button").click(function(){
search();
});
function search() {
var userInput = $("#content-container-search").val().replace(/\s+/g,"%20");
var searchTerm = "".concat(standardURL, apiKey, 'query=', userInput);
var request = new XMLHttpRequest();
request.open('GET', searchTerm , true);
request.onload = function(data) {
var data = JSON.parse(this.response);
if(data['results']){
data.results.forEach(film => {
if(film['title']){
console.log("film title : " + film.title);
}
});
}
}
request.send();
}
I think you need to understand the scope of each variable... if you do so, you can create a variable with greater scope, for example if you create a var data; outside the search function, and when you receive the data you do: data=JSON.parse(this.response); you will have access to data variable from outside the function
something like this:
$("#search-button").click(function(){
search();
});
var data;
function search() {
var userInput = $("#content-container-search").val().replace(/\s+/g,"%20");
var searchTerm = "".concat(standardURL, apiKey, 'query=', userInput);
var request = new XMLHttpRequest();
request.open('GET', searchTerm , true);
request.onload = function(data) {
data = JSON.parse(this.response);
data.results.forEach(film => {
console.log(film.title);
});
}
request.send();
}
There are two ways you can do as follow:
$("#search-button").click(function(){
search();
});
var firmList; // global variable
function search() {
var userInput = $("#content-container-search").val().replace(/\s+/g,"%20");
var searchTerm = "".concat(standardURL, apiKey, 'query=', userInput);
var request = new XMLHttpRequest();
request.open('GET', searchTerm , true);
request.onload = function(data) {
var data = JSON.parse(this.response);
firmList = data; // set data to global variable.
data.results.forEach(film => {
console.log(film.title);
});
}
request.send();
}
function test(){ // test external function
console.log(firmList); // will log the object
}
/*******************OR *****************/
request.onload = function(data) {
var data = JSON.parse(this.response);
test(data); // pass the object to another function.
data.results.forEach(film => {
console.log(film.title);
});
}
function test(_object){ // test function.
console.log(_object); // will log the parsed response object here.
}

Passing extra arguments to XMLHttpRequest.onload

I'm trying to comunicate with a server, using XMLHttpRequest in javascript.
How can I pass info to the onload function?
// global variable that containts server response
var reply;
var makeRequest = function(extraInfo) {
var request = new XMLHttpRequest();
request.open(...);
request.onload = handler;
};
var handler = function(data) {
reply = data.target.response;
console.log("Server Reply: " + reply);
};
How can I pass the parameter extraInfo from makeRequest to the handler function? (without using a global variable)
Just use a closure in such way:
...
var makeRequest = function(extraInfo) {
var request = new XMLHttpRequest();
request.open(...);
request.onload = function(data) {
// extraInfo is accessible here
reply = data.target.response;
console.log("Server Reply: " + reply);
};
};
I figured out that passing extra info into the request handler can be done this way: (At least is good for me)
request.open(...);
request.extraInfo = identifier;
request.onload = function() {
identifier = this.extraInfo;
};
The accepted solution didn't work for me, but this did
const params = new FormData();
params.append('selectedValue', selectedValue);
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.send(params);
xhr.extraInfo = extraInfo; // <- set your data here
xhr.onload = (e) => {
const data = JSON.parse(xhr.responseText);
alert(xhr.extraInfo) /// <- access it like this
alert(e.target.extraInfo) // <- or like this
//return data;
};

Acync JS HTTP Request Advice Request

I'm creating a javascript library for a project im doing that makes rest calls based on params you feed it. This is the second day of the project and I'm looking for advice. If I set my request to be async it returns my request but i can't access the object value, if I set it to false in the call it returns an object.
I read the stack articles on async js request, and I can't seem to wrap my head around call backs and promises.
this works:
request.open("DELETE", url, false);
this doesn't:
request.open("DELETE", url, true);
(function(window){
function defineCynergi(){
var Cynergi = {};
Cynergi.get = function(url){
var request = makeHttpObject();
request.open("GET", url, false);
request.send(null);
return JSON.parse(request.responseText);
}
Cynergi.delete = function(url){
var request = new XMLHttpRequest();
request.open("DELETE", url, false);
request.setRequestHeader('Accept', 'application/localhost.com:3000+json; version=1');
request.send();
deleteStatus = request.statusText;
return deleteStatus;
}
Cynergi.insert = function(url, data){
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader('Accept', 'application/localhost.com:3000+json; version=1');
request.send(JSON.stringify(data));
sentStatus = request.statusText;
return sentStatus;
}
Cynergi.update = function(url, data){
var request = new XMLHttpRequest();
request.open("PATCH", url, false);
request.setRequestHeader('Accept', 'application/localhost:3000+json; version=1');
request.send(JSON.stringify(data));
updateStatus = request.statusText;
console.log(request);
return updateStatus;
}
return Cynergi;
}
if(typeof(Cynergi) === 'undefined'){
window.Cynergi = defineCynergi();
}
})(window);
function makeHttpObject() {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
You should do something like this:
var request = new XMLHttpRequest();
request.open('GET', yourURI, true); // true = async
request.send();
request.onreadystatechange(function () {
if(request.readyState === 4){
/*ENTER CODE THAT SHOULD BE EXECUTED WHEN REQUEST IS DONE
(OPTIONAL)*/
switch(request.status) {
case 200: //DO STUFF
case 404: //DO OTHER STUFF
}
}
});
Or this:
var request = new XMLHttpRequest();
request.open('GET', yourURI, true);
request.addEventListener('load', function () {
//CODE THAT SHOULD BE EXECUTED WHEN SUCCES.
});
request.addEventListener('error', function () {
//CODE THAT SHOULD BE EXECUTED WHEN ERROR RESPONE.
});
request.send();

How to use sinon.js to fake the response of image

I'm learning how to use sinon.js. I can fake normal AJAX but I need to request a image and I don't get xhr.response (it is undefined). How can I use sinon.js to fake the response of an image?
var url = 'http://www.google.com.hk/logos/2013/antoni_gauds_161st_birthday-1539005.2- hp.jpg';
server.respondWith("GET", url, [200, {}, '']);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
//this.response is undefined
})
xhr.send(null);
How can I fake this image request?
I think an idea:
describe('...',function(){
var xhr;
before(function(){
xhr = sinon.useFakeXMLHttpRequest();
xhr.onCreate = function (x) {
console.log(x)
};
//....
}
after(function(){
xhr.restore();
});
it('....',function(){
xhr.prototype.response = new ArrayBuffer(1024)
// ...
});
}

Can't pass a DOM element to a constructor function in Javascript when trying to abstract section of WebAudio API xhr request

My problem is this. When I add an argument to the audioBoing function below and then place the same argument in the getElementById string, the function doesn't work. I get an error that says uncaught type error, cannot call method 'AddEventListener' of null
The function below works fine. I rewrote the function below it to reflect what I'm trying to do. Ultimately I am trying to abstract a good portion of the function so I can just plug in arguments and run it without having to rewrite it each time for each sound it stores / launches.
var playAudioFileOneDrumOneBig = function () {
var source = context.createBufferSource();
source.buffer = savedBufferOne;
source.connect(delay.input);
delay.connect(convolver.input);
convolver.connect(context.destination);
source.noteOn(0); // Play sound immediately
};
function audioBoing()
var xhr = new XMLHttpRequest();
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
context.decodeAudioData(xhr.response,
function(incomingBuffer1) {
savedBufferOne = incomingBuffer1;
var noteOneDrumOneBig = document.getElementById("noteOneDrumOneBig");
noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false);
}
);
};
xhr.send();
};
audioBoing();
ReWritten non-working
function audioBoing(yay) { //added yay
this.yay=yay; // defined yay
var xhr = new XMLHttpRequest();
xhr.open('get', 'audio/F.mp3', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function () {
context.decodeAudioData(xhr.response,
function(incomingBuffer1) {
savedBufferOne = incomingBuffer1;
var noteOneDrumOneBig = document.getElementById(yay); //passed yay
noteOneDrumOneBig.addEventListener("click", playAudioFileOneDrumOneBig , false); //error happens here
}
);
};
xhr.send();
};
audioBoing(noteOneDrumOneBig);
You didn't quote the string you passed to audioBoing
audioBoing("noteOneDrumOneBig");

Categories