XMLHttpRequest post function returned value (callback) - javascript

I want to make a callback function with returned value in XMLHttpRequest.
Ok so I can make it with $.get (example to show what I want to achieve).
$.get("/SomeFunction/", function (data) {
alert(data);
});
and I want to make the same with XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/SomeFunction/", true);
xhr.send();
I tried many ways to get the data value in XMLHttpRequest but I dont know how to make such working callback function. Any tips?

Ok, if someone will need it in the future, I found a solution:
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}

Related

How to return a response from xmlhttprequest javascript

I don't know why this function is returning undefined. Please help me... Run Snippet
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
return (this.response);
}
});
xhr.open("GET", url);
xhr.send();
}
let arr = xhr('https://reqres.in/api/users?page=2');
console.log(arr);
This is very very simple, Maybe you're new to Javascript, If you are not aware Js is an asynchronous language, it means that it would not block or wait for any function to complete which might be time consuming ( in this case a request to the server), This helps it to process other things meanwhile the request is taking place.
So in your case, it's creating the request to the server, but at the same time continues to execute your function and return the default value, i.e undefined, You can pass a callback to be called when the request is completed.
function callWhenFinished(arr) {
console.log(arr);
}
function xhr(url) {
const xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.addEventListener("readystatechange", function() {
if (this.readyState === this.DONE) {
callWhenFinished(this.response); // callback
}
});
xhr.open("GET", url);
xhr.send();
}
xhr('https://reqres.in/api/users?page=2');
you trying to make async request, but expect that it will work in synchronous way.
The way you solve your problem is:
use callbacks
use promises
use async/await (that's just wrapper of of promises)
i recommend you to use promises instead of XMLHttpRequest. it's easy to understand and it's modern way to work with requests.
related links here:
https://www.w3schools.com/js/js_callback.asp
https://www.w3schools.com/js/js_async.asp

How to everytime reload web, and get the newest data from back-end

What my purpose is below
Visting a web and the js.file in this web will load php file, and it will return data to html.
It's meaning every time when I reload web, I will get newest data.
I have try this in js.file
let XML = new XMLHttpRequest();
XML.open('post', url, true);
XML.send('mydata');
then use responseText to get data I want
Indeed, I don't need send any data.
I can do what I want to do, but I am not sure this way is right or not.
Because I think ajax should not use in this case, it must be send something and return something.
What you are saying is you only want to get data without sending anything which is called a http get request, you can do that as below.
function get(url)
{
var xm = new XMLHttpRequest();
// false for synchronous
xm.open("GET",url,false);
xm.send(null);
return xm.responseText;
}
console.log(get('your Url'));
You need to specify the url of your Http Endpoint ( Back-End ).
If your are making a asynchronous request then below code works,,
function get(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
// true for asynchronous
xmlHttp.open("GET", theUrl, true);
xmlHttp.send(null);
}
get('your url',(responseText)=>{
console.log(responsetext);
});

Unable to capture response from an API in Javascript

I am using below code to capture response but unable to get, please let me know what I am missing here.
function testcall() {
var request = new XMLHttpRequest();
request.open('GET', 'http://demo8951713.mockable.io/fusionchart', true);
request.send();
var response = this.responseText;
alert(response);
}
testcall()
You have two problems.
First, this (in the context you are using it) does not refer to your XHR object.
Second, you are trying to read the response as soon as the request has been sent. You have to wait until the browser has received the response!
request.addEventListener("load", function () {
var response = this.responseText;
alert(response);
});
That change (moving the code to an event handler) also puts this in a context where it refers to the correct object.
Once you have fixed this, you are likely to want to try to return the value. Before you do, read this question.
you are missing the callback function
request.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.response);
}
}
for more details, refer https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response#Example

Empty response of XMLHttpRequest

In my Java Web application I am calling ajax request as below.
<script type="text/javascript">
function selectTableHandler() {
console.log("indise selectTableHandler");
var xhttp = new XMLHttpRequest();
var selectedTable = document.getElementById('selectTable').value;
alert(selectedTable);
xhttp.open("GET", "populateTableColumList.action?tablename="
+ selectedTable, true);
xhttp.send();
console.log(xhttp.responseText);
}
</script>
The Action is calling and returns status code 200 as below.
Remote Address:[::1]:8080
Request URL:http://localhost:8080/ReportBuilder/populateTableColumList.action?tablename=films
Request Method:GET
Status Code:200 OK
But, it gives empty response of XMLHttpRequest. The line console.log(xhttp.responseText); prints nothing. Also, there is no error in console log.
Any suggestions would be appreciated.
Thanks
You need to add a callback function to get the result of the ajax request.
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
Your ajax request is asynchronous. That means it returns the result some time LATER. You will need to install an event handler for onload or onreadystatechange to get the result.
There are plenty of Ajax tutorials on how to do this. Here are a couple useful references:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
If you want to use vanilla js you have to attach event handler onreadystatechange which will handle response, but my advice instead of use vanilla js, use library like jQuery to initiate the ajax request. It will be more easily and it will run without problems on all types of browsers. see here. If you want vanilla js, here is a sample snippet:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE ) {
if(xhttp.status == 200){
console.log(xhttp.responseText);
}
}
}

HTTP HEAD Request in Javascript/Ajax?

Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?
My motivation is to conserve bandwidth.
If not, is it possible to fake it?
Easy, just use the HEAD method, instead of GET or POST:
function UrlExists(url, callback)
{
var http = new XMLHttpRequest();
http.open('HEAD', url);
http.onreadystatechange = function() {
if (this.readyState == this.DONE) {
callback(this.status != 404);
}
};
http.send();
}
This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different event handlers (onload, onerror and ontimeout rather than onreadystatechange).
An XMLHTTPRequest object should have
getAllResponseHeaders();
getResponseHeader("header-name")
defined on it

Categories

Resources