can xmlhttpRequest response wait even after onload - javascript

I am loading a page through xmlHttpRequest and I am not getting one variable which come into existance after some miliseconds when page loading is done
so the problem is when xmlHttpRequest sends back the response I do not get that variable in it.
I want it to respond back even after onload.
var xhr = new XMLHttpRequest();
xhr.open("GET", event.url, true);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() { callback(); };
xhr.followRedirects = true;
xhr.send();
I tried setTimeOut but of no use because may be at that time call is finished
xhr.onload = function() {
console.log('wait for response');
setTimeout(function(){
callback(xhr.responseText);
},2000);
};
I tried readyStateChange , but no success
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
callback(xhr.responseText);
};
};
by the way, I am trying to load amazon signIn page
and the variable which is missing everytime is hidden Input Field metadata1,
I get all other hidden Input fields in response text , except input field, named "metadat1"
I'll be more than Happy, If anyone can help.
Thanks in advance

ohh Finally I did it,
I din't read any javascript, Instead I just extracted scripts which I received in xhr calls and executed it inside a hidden div, and here it is , I got that variable's value
abc(xhr.responseText);
function abc(xhrRes){
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrdiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var scr = document.getElementById('xhrdiv').getElementsByTagName("script");
//5 scripts needed to generate the variable
for(i=0;i<5;i++){
eval(scr[i].innerHTML);
if( i+1 == 5){
var response = document.getElementById('xhrdiv').innerHTML;
return response; //and in this response variable I have every thing I needed from that page which I called through xmlhttp Req
}
}
}
---------------------Improved Version-----------------------
Instead of executing script through eval,
keep script content in a file AND Include it, as we normally include the script, that works better.
xhrRes = xhr.responseText;
var dynamicElement = document.createElement('div');
dynamicElement.setAttribute("id", "xhrDiv");
dynamicElement.setAttribute("style", "display: none;");
dynamicElement.innerHTML = xhrRes;
document.body.appendChild(dynamicElement);
var xhrDiv = document.getElementById('xhrDiv');
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = JSfile;
xhrDiv.appendChild(newScript);
(it shows the edit is done my anonymous user, :( because I forgot to Login, while editing)

If the data doesn't exist until some time after the page has loaded then, presumably, it is being generated by JavaScript.
If you request the URL with XMLHttpRequest then you will get the source code of that page in the response. You will not get the generated DOM after it has been manipulated by JavaScript.
You need to read the JavaScript on the page you are requesting, work out how it is generating the data you want to read, and then replicate what it does with your own code.

Related

Javascript - Is it possible to change location, and start manipulating the new document

I'm trying to switch between pages and then to manipulate the new document through javascript or jQuery.
However, when I run my example, it manipulates the first document and then changes location. Is it even possible?
this is my example(i even tried to call a function after changing location):
function openSide(x) {
//é passado o botão carregado
window.location.href = 'new.php';
var id = x.innerHTML;
open(id);
}
function open(x) {
$("#div1").css("display","none");
$("#div2").css("display","");
$("#tituloPlay").html(id);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$("#tabelaOuvirPlaylist").append(xhttp.responseText);
//console.log(xhttp.responseText);
}
};
xhttp.open("POST", "php/listarMusicasDePlaylist.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+ x);
}
Use the jQuery load() method to take data from that location and put it on your page. Then you can manipulate it from there.
Since you're opening a new PHP page, why don't you just pass the ID as a query parameter?
new.php?id=1
Adjust your PHP file to read the ID from $_GET ["id"]..
To use the ID in Javascript you would need to read the current location and do a substring the = sign or you could have PHP create a hidden DOM element and read it's value in Javascript

XMLHttpRequest sends url as response text, Firefox doesn't redirect

I have some javascript that sends a XMLHttpRequest to a PHP file. This PHP file sends a response, and javascript is supposed to create a URL and redirect to it, using the response text as a parameter. In all other browsers it works fine, but Firefox won't include the response text in the URL.
This is the javascript example:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'filename.php', true);
xhr.onreadystatechange = function(e){
var id = e.currentTarget.responseText;
var urlWithId = "restofurl?id=" + id;
window.location.href = urlWithId;
}
xhr.send(fd);
and filename.php is just a number at the moment:
<?php
echo "3";
?>
I have tried putting other parts of the url (up to the whole url) in the php part, and firefox always cuts out exactly that part. I have also tried copying the response several times to different variable, copying it character by character, putting it in a function that just returns the input again,...
This is only going to be on my own computer, so I don't need to worry about any security issues, so I'm mostly looking for an easy way to cheat around this rather than the way it would be done professionally. Does anyone have any idea?
This is a basic example, you actually have to test readyState status. If i remember well, it is also safer to set the event function before sending the request (not really sure of that).
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
//do something with this.responseText
}
};
xhr.open("POST", url, true);
xhr.send();
EDIT:
This is one of the reasons why i use frameworks, for the old browser support, but this is not an answer. To be more precise, in the past (present?), browsers used to implement exotic functions. It's been a long time i didnt bother to use XHR objects directly, last time it was for file uploads with loading bar (canvas). It shows you the basic way to handle some stuff. This is longer and a bit old fashioned, but well, it works.
function customXHR(){
if(window.XMLHttpRequest){
return new window.XMLHttpRequest;
}else{
try{ //the weird ones
return new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
catch(ex){
return null;
}
}
}
var xhr = customXHR(), pleaseStop = false, startDraw = false;
if(xhr){
xhr.addEventListener('load', function(e){
var jsonRep;
if(!pleaseStop){
//did use a JSON response
jsonRep = $.parseJSON(e.target.responseText);
//do the rest, we finished
}
}, false);
xhr.addEventListener('error', function(e){
//error
pleaseStop = true;
}, false);
xhr.upload.addEventListener('progress', function(e){
//why not let this as an example!
//file_size must be retreive separately, i fear
if(e.lengthComputable && file_size > 0 && !pleaseStop && startDraw){ draw_progress(e.loaded / file_size); }
}, false);
xhr.addEventListener('loadstart', function(e){
//can be used too
}, false);
xhr.addEventListener('readystatechange', function(e){
if(e.target.status == 404 && !pleaseStop){
//error not found
pleaseStop = true;
}
if(e.target.readyState == 2 && e.target.status == 200){
startDraw = true;
}
/*if(e.target.readyState == 4){
//not used here, actually not exactly the same as 'load'
}*/
}, false);
xhr.open("POST", url, true);
xhr.send();
} //else no XHR support

jQuery reloading incorrectly

I am making a little script to change website language using PHP and Ajax/jQuery. I want page content to refresh without reloading page. Until now i have made this
$( "a[data-request]" ).click(function() {
var xhr = new XMLHttpRequest();
var request = $(this).attr('data-request');
var what = $(this).attr('data-to');
xhr.open('GET', '{{ site_url }}' + what + '/' + request);
xhr.onload = function() {
if (xhr.status === 200) {
$("#body").load(location.href + " #body");
}
};
xhr.send();
});
When i click on link
<a data-request="english" data-to="home/language" href="#">
It succesfuly performs uri request in background and "reloads" #body element, which is whole body
<body id="body">
However instead of reloading whole page content just disappear and wont reappear again. What am i doing wrong?
Replace xhr.onload because it's not implemented in all browsers, use onreadystatechange instead
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK)
$("html").html(xhr.response);
}
};
xhr.open('GET', '{{ site_url }}' + what + '/' + request); //<-- note must come after above event handler
note : this would wipe your button too(one you clicked to fetch the page).so instead of body load that data in some div.
EDIT
I suppose your code is something like this
$(document).ready(function(){
$(langDropdown).change(function(){
//get selected language
//do ajax
});
});
Now suppose you change lang. to Spanish server sends you a Spanish version so what you get from server is bit like
<html>
<head> ....title.....
<script src=....></script> //common libs like jquery etc
<script src=my.js></script> //this would be js contaning above code
</head>
<body>
Esta es una pagina
</body>
</html>
Now when you use document.write to put the Italian page the document.ready won't get called(why? because it gets called only on actual page refresh) so change event handlers wont get bound on lang. selection dropdown
Solution:
code outside document.ready will definitely run even when fetched through ajax, but i won't advise that , rather what i would advise is whatever code you want to run on ajax completion (like event binding) write it after document.write is success callback/readyState
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE && xhr.status === OK) {
$("html").html(xhr.response);
$(langDropdown).change(function(){
//binding code
});
}
};

How should I create two object to do two different ajax calls?

I have:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
document.getElementById('content').innerHTML = xhr.responseText; // Update
}
};
xhr.open('GET', 'data/data-one.html', true); // Prepare the request
xhr.send(null);
Now I want to do the same thing for another link, so when the link is clicked, in the code above, data-one.html is inserted to the HTML container with an id of content in my html page.
Now lets image I have another link in my nav and want to do the same process for another html container with an id of content1 this time to insert data-two.html .
Do I have to create the httprequest in this file or another ajax file? Are the variables gonna be different?
I already tried with the same variable both in the same file and other files but I get an error saying the I can't set the innerHTML to Null. I can't find out why. Please help.
This code is just to get you started. It is very verbose and can be improved to reused. For the sake of clarity I decided to keep it simple though.
function reqListener1 () {
console.log("listener1 -- html echo", this.responseText);
}
function reqListener2 () {
console.log("listener2 -- json echo", this.responseText);
}
document.addEventListener("DOMContentLoaded", function () {
var url1 = "/echo/html/";
var url2 = "/echo/json/";
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener1);
oReq.open("GET", url1);
oReq.send();
// you could use the same variable. but you'll need to instantiate a different object
var oReq2 = new XMLHttpRequest();
oReq2.addEventListener("load", reqListener2);
oReq2.open("GET", url2);
oReq2.send();
});
Demo: http://jsfiddle.net/pottersky/7dz8r19d/1/

Load an xhtml file to a div element using CORS and javascript

I want to load a page from another domain to a div element in my page. I'm using CORS and it works since it shows the file is loaded in console log but I cannot manage to add it to my div.
Here's my code to make it more clear:
<script type="text/javascript">
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "http://localhost:8080/test/header.xhtml");
if (request){
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status >= 200 && request.status < 400) {
var hpage = request.responseText;
document.getElementById("theader").innerHTML = hpage;
} else {
alert("An error occured! Request Status: +"request.status);
}
}
};
request.send();
}
</script>
<body>
<div id="theader"></div>
</body>
How do I display the loaded page in theader div?
UPDATE
I found out that this happens in firefox and chrome because I use localhost. It works in ie but it only loads the text without css and images. Any idea how can I load the whole page into the div?
I guess my question now will be does the page load with all resources in CORS like it does with iframe? If so how?
A div element is meant to contain only certain HTML elements: in a nutshell the elements that you can find in the body. But not all HTML elements, and in particular not a html or head element. This is why your code does not work.
To solve your problem you either need to use an iframe (but from your question it seems this is not what you want), or put the content of the body element in the div and parse the head and load it in the current head.
Something like that (not tested):
var hpage = document.createElement("html");
hpage.innerHtml = request.responseText;
//Below you might want to write more robust code
//depending on the content of the response and how much you trust it
var head = hpage.getElementsByTagName("head")[0];
var body = hpage.getElementsByTagName("body")[0];
document.getElementById("theader").innerHTML = body.innerHTML;
//Now iterates over the children of head to find
//the script and style elements, and you can append them to the head of the document
var currentHead = document.getElementsByTagName("head")[0];
var scripts = head.getElementsByTagName("script");
for (var i=0; i<scripts.length; i++) {
currentHead.appendChild(scripts[i]);
}
//same thing for style elements,
//you could even do that for all elements
//depending on what the response may contain

Categories