Receive Single Data from xml - javascript

I have brought some data from the server using ajax.
Now I want to, not bring all the data, only the name is inter.
How can I do this?
that my code
const url = 'https://jsonplaceholder.typicode.com/users'
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
console.log(xhr.response);
}
xhr.open('GET', url)
xhr.send()

You could loop through the xhr response and get the name of the users.
xhr.onreadystatechange = () => {
if(xhr.response) {
let userResponse = JSON.parse(xhr.response);
for (index in userResponse) {
console.log(userResponse[index].name);
}
}
}
You can even save it in a temporary variable and make further manipulations.
But if you meant bringing just the name from the server, it is not possible unless the server exposes an API to do so.
If you have access to the server you could create an API to do this. But, if your server had used graphQL, it is possible to make queries while making API requests like you asked for.

Related

How to listen for HTTP call in front end JS

I am working on a site, which uses a 3rd party library to launch a pop up to collect users email addresses.
After the user submits the email address, the 3rd party API is called, following the format https://<API-URL>/collectemail?email=test%40test.com
I want to run a function when that API is called and pass it the email param. How can I listen for that event and then trigger my function?
The best way would be to fork the library and modify it so that, when the API is called, the library code itself calls the code on your site with the email parameter.
If that's not possible, your only other option is to monkeypatch XMLHttpRequest so as to intercept requests, such as with:
// Your code, make sure this runs first:
const origXHR = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
const xhr = new origXHR();
xhr.open = (method, url) => {
origXHR.prototype.open.call(xhr, method, url);
console.log('Connection just opened to:', url);
}
return xhr;
};
// Library code:
const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/?email=test%40test.com');
xhr.send();

How can I override javascript XHR prototype to send and receive data from a websocket

I'm trying to do something really weird / stupid, I'm trying to build a kind of a Websocket proxy for XHR requests.
Lets say that you have a component on the page that is constantly requesting resources by XHR (GET's) and this is the flow I want to achieve:
Intercept the XHR GET request (done);
Forward it through a Websocket (done);
The server takes the URL and params, makes the call to the remote endpoint and returns the data via Websocket back to the client (done);
Inject the response received by the Websocket back to the original XHR GET and finish it (not done)
So my trouble right now is not being able to "emulate" the finish of the XHR request with the response data from the Websocket, is there any event that can be triggered or a method?
Can someone please give me some ideas or solutions regarding this?
My current code:
XHR.prototype.open = function (method, url, async, user, pass) {
const self = this;
function getter() {
console.log('get responseText');
delete XHR.responseText;
// var ret = XHR.responseText;
}
function setup() {
Object.defineProperty(XHR, 'responseText', {
get: getter,
configurable: true
});
}
setup();
socket.emit('req', url);
socket.on('reqr', data => {
var event = new Event('loadend');
setup();
self.dispatchEvent(event, data);
// return data;
});
// this._url = url;
// open.call(this, method, url, async, user, pass);
}

Why does this email sending function not work?

Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.

How to use my local API in a javascript file?

I have a file api.js which contains something along the lines of this:
exports.showAll = function(req, res) {
Obj.find(function(err, Objs) {
res.send(Objs);
});
}
My server has the line:
app.get('/all', api.showAll);
When I load /all in the browser, I get the JSON, but I want to get this JSON into a client-side JS file, so I can display the JSON data beautifully on a webpage.
How do I use my server-side API in a client-side JS file?
To make a call to a server and work with the result, you need to use AJAX. AJAX stands for Asynchronous JavaScript and XML but the reality is that you can make these kinds of call through other languages and without retrieving XML. Here's a simple example of how to make a request to your server:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
// Verify that the request is done and completed successfully
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var json = xhr.responseText;
var data = JSON.parse(json); // Parse the JSON into an actual object/array
console.log(data);
} else {
console.log('Something went wrong');
}
}
};
xhr.open('GET', '/all');
xhr.send();

How to get only response headers from XMLHttpRequest

Is it possible to get only response headers from XMLHttpRequest without downloading file data?
If the server you are making the request to supports the method, it sounds like what you want is to make an HTTP HEAD request. See the HTTP spec.
For example compare the output from curl -v -X GET https://github.com and curl -v -X HEAD https://github.com.
Also see HTTP HEAD Request in Javascript/Ajax?
Using JavaScript (as specified in the question) simply use a head request via AJAX:
var xhr = new XMLHttpRequest();
var method = 'head';
var url = 'https://www.example.com/';
xhr.open(method,url,true);
xhr.send(null);
xhr.onreadystatechange = function()
{
if (xhr.readyState === 4)
{
console.log(xhr.getAllResponseHeaders())
}
}
Firstly, the answer from John fixes this issue but it got downvoted because it didn't have enough of an explanation.
So here is the fix with an explanation as well as an extra bit that you can add as well.
Client side solution is as follows (I am using the status code as the example):
function checkStatus(url) {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('HEAD', url, true)
request.onreadystatechange = () => {
if (request.readyState >= 2) {
resolve(request.status)
request.abort()
}
}
request.onerror = (e) => {
reject(e)
}
request.send()
})
}
The reason why this works is for two reasons.
Firstly we are passing HEAD in as the method instead of GET this should be enough on its own, but if you want to do more, you can move onto the second reason.
The second reason this works is because of the readyState states.
0 = UNSENT
1 = OPENED
2 = HEADERS_RECEIVED
3 = LOADING
4 = DONE
At state 2 the headers are ready to be viewed. This means you can then return whatever you need and/or abort the rest of the request preventing any further data being downloaded.
Worth noting you can also do this with request.onprogress at stage 3.
See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState and https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods for more details.

Categories

Resources