Passing extra arguments to XMLHttpRequest.onload - javascript

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;
};

Related

How do I make multiple API calls via XMLHttpRequest?

I'm not that experienced when it comes to APIs so excuse me in advance.
I'm trying to get a button to display the contents (response) of an API, and the code below works wonders. I'm wondering how I would make the exact same request, but instead of the "explicit" endpoint, I want a "history" endpoint instead.
How would I do this?
const data = null;
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var object1;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object1 = JSON.parse(this.responseText);
}
document.getElementById('thejoke').innerHTML = object1.value;
});
xhr.open("GET", "https://api.chucknorris.io/jokes/random?category=explicit");
xhr.send(data);
The simplest answer would be to make it a function:
function send(category) {
const url = "https://api.chucknorris.io/jokes/random?category=" + category
const data = null;
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
var object1;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object1 = JSON.parse(this.responseText);
}
document.getElementById('thejoke').innerHTML = object1.value;
});
xhr.open("GET", "");
xhr.send(data);
}
And then you can you call it like this:
send("explicit");
The only problem you then face is that object1 is not available outside of the function. You could work around this by making object1 a global variable, or do the things you want to directly in the EventListener.

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.
}

Reading JSON data from a url using javascript

I want to read data from this link http://starlord.hackerearth.com/gamesext.
I went through this https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON and was able to obtain data from https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.
Trying similar approach for getting data from http://starlord.hackerearth.com/gamesext is not working for me.
This is how I tried:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var games = request.response;
document.getElementById("para").innerHTML = "for check";//para is a paragraph id
fun1(games);
}
function fun1(jsonObj){
//getting first title
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
I would want to know is that data in JSON and how to get it?
Try using the JSON.parse() method:
function fun1(jsonObj){
//getting first title
jsonObj = JSON.parse(jsonObj);
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
This will turn valid JSON into a javascript object that can be accessed as you are trying to do below.
This works perfectly fine for me:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.response[0].title) # LittleBigPlanet PS Vita
}
};
xhttp.open("GET", requestURL);
xhttp.responseType = 'json';
xhttp.send();
Give it a try!
Using fetch this is pretty simply.
Below is an example.
const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
async function getData() {
const json = await (await fetch(url)).json();
console.log(json);
}
getData();
just put request.send(); after all the code you provided.

How do I pass a variable to into HttpRequest?

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);
});

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