I have a situation where if browser window is closed then i need to make an XmlHttpRequest and show the result in a pop before the window is closed. But in my current code the browser doesn't wait for XmlHttpRequest to complete as it is asynchronous and closes the window. how can i open a pop before the browser closes itself.
var xhr = new XMLHttpRequest();
window.onbeforeunload = sendRequest();
//method to send the request to server
function sendRequest(){
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
}
the result(alert) should be visible before window is closed.
You can make change little bit in your JS codes:
Referred from documentation link: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example
where we need to cancel the event as stated by the browser, events like refreshing/ reloading a page or going to back page.
function sendRequest(event){
event.preventDefault();
event.returnValue = '';
var __type= event.currentTarget.performance.navigation.type;
// __type === 1 || __type === 0 : comes when Browser refresh button is clicked...
// __type === 2 : Browser back button is clicked
if(__type === 1 || __type === 0 || __type ==2){
// write here your AJAX request code or you can create a function for AJAX request & call up that function
xhr.open('GET', "https://www.google.co.in/search?q=java", true);
xhr.send();
xhr.onreadystatechange = processRequest;
}
}
//method to process the output
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var xmlDoc = xhr.responseText;
alert(xmlDoc);
}
// here you can write a code to close the browser window
}
Related
It is my AJAX call with setTimeout
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById('mainContent').style.display = 'none';
if (this.readyState == 4 && this.status == 200) {
xhttp.onload = function(){
document.getElementById("mainContent").innerHTML = this.responseText;
setTimeout(function(
document.getElementById("mainContent").style.display = 'block';
),1000);
}
}
};
xhttp.open("POST", "system.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lang="+lang);
I want detect when ajax is fully loaded and I have also solution here
I have solution here but I can't understand how it work.
var oldOpen = XMLHttpRequest.prototype.open;
function onStateChange(event) {
// fires on every readystatechange ever
// use `this` to determine which XHR object fired the change event
}
XMLHttpRequest.prototype.open = function() {
// when an XHR object is opened, add a listener for its readystatechange events
this.addEventListener("readystatechange", onStateChange)
// run the real `open`
oldOpen.apply(this, arguments);
}
Can you example me how it work or write full code how it work ?
i want to check if a local file exists, if it not exists i want to run an alert('File not exists!').
I tried something like this :
function isOnline() {
var xmlPath = "/test/test/myfile.xml"
var request=new XMLHttpRequest();
request.open("GET",xmlPath,false);
request.send();
if (request.readyState === 4){
return true;
}else{
alert('File Away!');
return false;
}
}
But this dont work.
i cant use PHP or jquery.
If you try to get a resource from a server means the file should be publicly accessible through an URL.
When you launch that request with the XMLHttpRequest object with request.send() that call is asynchronous so checking immediately the readyStateor status it will not assure you the end of the call.
function isOnline() {
var xmlPath = "/test/test/myfile.xml"
var request=new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("File was found on URL");
}else if (this.readyState == 4 && this.status == 404 ) {
alert("File away!");
}
};
request.open("GET",xmlPath,false);
request.send();
}
You should subscribe to the status change event and check the values of that change. So beyond checking for the readyState==4 to get the change to the end of the transaction you should check also for the status code. For example 200 means everything was ok or 404 means the resource was not found.
Check the specification for that codes here:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I am trying to update a feed when a user gets to the bottom of the page and add the new content. It for some reason is not returning the content at all.
Here is my jquery/javascript
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $(document).height() - 650){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("thumbs").innerHTML = xmlhttp.responseText;
}
else {
document.getElementById("thumbs").innerHTML = "Error Occurred.";
}
}
xmlhttp.open("GET", "include/update-gamer-feed-curl.php", true);
xmlhttp.send();
}
});
The php file already works because it gets the first ten items already and I am just calling it again to get the data to reload into the screen so I can prepare to append what is needed once I get more elements.
It is telling me the xmlhttp is depreciated. I have also tried using
$.ajax({url: "include/update-gamer-feed-curl.php", success: function(result)
{
$("#thumbs").append(result);
}
but this doesnt work either. I know it is in this because if I put the string test in the append element where result is it appends the test string.
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 650){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/echo/json/", true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200) {
document.getElementById("thumbs").innerHTML = xmlhttp.responseText;
}
else{
console.log("Error: rState=" + xmlhttp.readyState + ", status=" + xmlhttp.status);
}
}
}
}
}, 250));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It seems the request is repeated too much. A timer of 250ms helped some, but still, the innerHTML is overwritten too fast. So I also change so that innerHTML is written to if success, but console gets the error. readyState 1,2,3 is repeated many many times when scrolling, and causes many errors. Avoided by checking readtState == 4 first.
Here are the description of the readystates
0=The current object is not initialized (the open method has not been
called yet).
1=The request is opened, but the send method has not been called yet.
2=The request is sent but no data has been received yet.
3=A part of the data has been received, but it is not yet available.
4=All data is available.
Make sure readyState == 4 first, and then checks the status. And by moving open and send above onreadystatechange, you avoid readystate errors 0 and 1.
On a webpage, once images have been downloaded and rendered, I need to determine an image's file size (kb) within the browser context (so I could display that info on the page, just below the image)
The easiest way is probably with a HEAD request returning the Content-Length:
function fileSize(img, func) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', img.src, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
func(xhr.getResponseHeader('Content-Length'))
}
}
xhr.send()
}
Usage
fileSize(imgNode, function(size) {
// ...
})
I'm trying to create an Ajax request and then parse the response header to get the "Location" attribute. This is my code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
}
request.open('GET', hrefAttr, true);
request.send(null);
The problem is that for some reason, the request is send and the response is received too (red "GET" request+response in Firebug), but I don't get any "test" alert nor any text in the firebug console.
EDIT: This is the modified code :
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
console.log(request.readyState);
if(request.readyState <= 3 && request.status == 301) {
alert('test');
var header = request.getResponseHeader('Location');
console.log(header);
}
else if (request.readyState == 0 && request.status == 301) {
alert('state0');
}
}
request.open('GET', hrefAttr, true);
request.send();
console.log(request.readyState) gives this sequence of states : 1, 1, 2, 4.
In the Firebug console tab the Http Request+Response show fine but in red (if that means anything).
Not sure why I it isn't working...
Edit : I'm using Firefox.
Thanks in advance !
Unfortunately, the XHR will follow the 301 and return the content of the redirected page. You can see the behavior documented at the W3C here.
If the XMLHttpRequest origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.
So basically, your request is following the 301 transparently. The browser is automatically redirected and you are unable to do what you intend to do. If you have control over the web server, this can be changed (albeit, against most advice).
Hope this helps!