PHP backend with JS xHTMLRequest frontend - javascript

In JS, I wanted to create a function that made a xHTMLRequest to a backend PHP server, problem is I want JS to wait for the response, otherwise it will display 'undefined'.
function xhrReq(method, args) {
let xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(args);
xhr.onreadystatechange = ()=> {
if(xhr.readyState == 4) {
return xhr.response;
}
}
How can I make this function return the response value?

You can use fetch in a async function:
(async () => {
try {
//const args = ...;
var headers = new Headers();
headers.append("Content-Type", "application/x-www-form-urlencoded");
const response = await fetch('http://localhost/example/php/example.php', {
method: 'POST', // or other
headers,
body: args
});
} catch (err) {
//process error
}
})()
or you can promisify your function :
function xhrReq(method, args) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, 'http://localhost/example/php/example.php');
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject(Error(`XHR request failed. Error code: ${xhr.statusText}`));
}
};
xhr.onerror = function() {
reject(Error('There was a network error.'));
};
xhr.send(args);
});
}
And use it in a async function (or use promise) to get the response.

Related

put the data from an api link using this function and console.log it

I want to use a variable which has the JSON data to later parse and stringify it
all i want now is to see the actual array of objects in the console!
console.log(fetchJSON('url'));
function fetchJSON(url, cb) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
if (xhr.status < 400) {
cb(null, xhr.response);
} else {
cb(new Error(`Network error: ${xhr.status} - ${xhr.statusText}`));
}
};
xhr.onerror = () => cb(new Error('Network request failed'));
xhr.send();
}
I expect the output of console.log(fetchJSON('url'));
to be
Try this:
fetchJSON('url', function(result) {
console.log(result);
});
Your function fetchJSON is returning a callback function. If you want to return just the result change
this
cb(null, xhr.response);
to:
return xhr.response;

How to do XHR in Azure Function App

I want to fire an http API and process it's response but I am getting following error:
Exception while executing function: Functions.getAccessObject. mscorlib: ReferenceError: XMLHttpRequest is not defined
Here's my Azure serverless function Code:
module.exports = function (context, req) {
function getAccessObject(context, successCallback, failureCallback) {
var APPLICATION_ID = "zzz";
var APPLICATION_SECRET = "zzz";
var REFRESH_TOKEN = "zzz";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("GET", "https://xyz");
xhr.setRequestHeader("applicationid", APPLICATION_ID);
xhr.setRequestHeader("applicationsecret", APPLICATION_SECRET);
xhr.setRequestHeader("refreshtoken", REFRESH_TOKEN);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
successCallback(context, request.responseText);
} else {
failureCallback(context, request.responseText);
}
}
};
request.send(null);
}
getAccessObject(context, registerForWebhookFunc, failureCallbackFunc);
}
I believe XHR is a browser API and not native to node.js. You can use the built-in http functionality of node.js (see example below) or alternatively other popular packages are available such as Axios that can do http requests. I believe there may even be one for XHR if you are set on using that.
const https = require('https');
https.get('http://myapi', (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(JSON.parse(data));
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}

Promise returning undefined after sending value to the server

I just started making use of the promise function in javascript, and i do like it, but i am running into an issue.
I am getting a value from a promise object, and then sending the response back to the server in an asynchronous promise function. When i send the value back to the server, and try to see what the value is, it returns undefined.
var xhr = new XMLHttpRequest();
function createFirstChannel(method, rippleApi) {
return new Promise(function (resolve, reject) {
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4 ) {
var hashValue = resolve(JSON.parse(xhr.responseText));
}
else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send(json);
});
}
A value gets returned from the first function which i am using in the next promise function
async function createChannel(method, url) {
var datums = await createFirstChannel(method, url);
//method to return hash value from json request
for (var key in datums) {
var tx_json = datums[key]['json'];
datums = (json['hash']);
console.log(datums);
}
//creating the json request to send back out again using POST METHOD
var channel= {
"method": "tx",
"par": [{
"transaction": datums
}]
}
var jsonPayee = JSON.stringify(channel);
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function () {
if (xhr.readyState == 4) {
users = JSON.parse(xhr.responseText);
}
};
xhr.send(jsonPayee);
return users;
}
createChannel(method, url).then(datums => {
console.log(datums);
}).catch(function (err) {
console.error('Sorry There Was An Error!', err.statusText);
});
i get "undefined" response at console.log. is there any way to resolve this error? Thanks for the help

Got undefined from the CORS API call in React

I am trying to call a REST API hosted locally using CORS, and fetch the data to visualize on my front-end wrote using React. But I keep getting undefined from the data fetch function, and the function works well when I console out the data in the 'onload' handler. Here are my two scripts doing data fetching:
// App.js
import {fetchIntradayDataHR, fetchDailyLogHR} from './DataFetch';
// ...
componentWillMount() {
// Called the first time when the component is loaded right before the component is added to the page
this.getChartData();
}
getChartData() {
var url = "http://127.0.0.1:8080/heart";
// var response = fetchIntradayDataHR(url);
console.log(fetchIntradayDataHR(url));
*// Got undefined here.*
this.setState({ ... });
}
// DataFetch.js
// Helper function to sort out the Browser difference
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
export function fetchIntradayDataHR(url) {
var xhr = createCORSRequest('GET', url);
if(!xhr) {
alert('CORS not supported!');
return {};
}
xhr.onload = function() {
var parsedResponse = JSON.parse(xhr.responseText);
var parsedObj = renderIntradayData(parsedResponse);
console.log(parsedObj);
// Got the correct result here tho...
return parsedObj;
};
xhr.onerror = function() {
alert('Error making the request!');
return {};
};
xhr.send();
}
// ...
fetchIntradayDataHR is an asynchronous function . Then , you need to pass a callback to be running when the response comes .
So, the first change is the signature of fetch function :
export function fetchIntradayDataHR(url, onSuccess, onLoad) {}
instead of
export function fetchIntradayDataHR(url) {}
Then in the React Component, you will call this function accordingly and the callback will includes this.setState :
var url = "http://127.0.0.1:8080/heart";
const onSuccess = (response) => this.setState({ok : true});
const onError = (error, response) => this.setState({ok: false});
fetchIntradayDataHR(url, onSuccess, onError);
instead of
var url = "http://127.0.0.1:8080/heart";
// var response = fetchIntradayDataHR(url);
console.log(fetchIntradayDataHR(url));
this.setState({ ... });
Brief you code can as the following :
// App.js
import {
fetchIntradayDataHR,
fetchDailyLogHR
} from './DataFetch';
// ...
componentWillMount() {
// Called the first time when the component is loaded right before the component is added to the page
this.getChartData();
}
getChartData() {
const url = "http://127.0.0.1:8080/heart";
// var response = fetchIntradayDataHR(url);
const onSuccess = (data) => this.setState({data: data, fetching: false}); //!--- ⚠️ ATTENTION
const onError = (error) => this.setState({message: error, fetching: false}); //!--- ⚠️ ATTENTION
this.setState({fetching: true}); // start fetching
fetchIntradayDataHR(url, onSuccess, onError); //!--- ⚠️ ATTENTION
console.log(fetchIntradayDataHR(url)); * // Got undefined here.*
this.setState({...
});
}
// DataFetch.js
// Helper function to sort out the Browser difference
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
export function fetchIntradayDataHR(url, onSuccess, onError) {
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported!');
return {};
}
xhr.onload = function() {
var parsedResponse = JSON.parse(xhr.responseText);
var parsedObj = renderIntradayData(parsedResponse);
console.log(parsedObj);
// Got the correct result here tho...
onSuccess(parsedObj); //!--- ⚠️ ATTENTION
return parsedObj;
};
xhr.onerror = function() {
onError('Error making the request!'); //!--- ⚠️ ATTENTION
return {};
};
xhr.send();
}
// ...

Upload image to firebase from hybrid app

how can I upload an image from his path "file:///var/mobile/Containers/Data/Application/D6326867-A474-481F-B6B4-5A9A6251CC0E/tmp/cdv_photo_013.jpg" to firebase storage using Javascript ? Cause I know how to using Blob or File but not from a single path...
Here my resolved code :
uploadPicutre(uri:string, userUid: string){
let self = this;
return new Promise((resolve, reject) => {
function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.send();
}
toDataUrl(uri, blob => {
self.refStoragePicture.child(userUid)
.put(blob).then(snapshot => {
self.refStoragePicture.child(userUid)
.getDownloadURL().then(function(url) {
resolve(url);
}).catch(function(error) {
reject(error);
});
}).catch( err => {
reject(err);
});
})
})
}

Categories