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

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/

Related

How to access Dom elements inserted by XMLHttpRequest?

I am loading html files with an XMLHttpRequest and putting everything in the body tag into an unseen 'storage' div, and then into the page to be seen. That works well.
function getModule(module,callback) {
var modulePath = makeModulePath(module);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ) {
var el = document.getElementById('storage');
getContent(xhr.responseText, el);
callback(el);
}
};
xhr.open("GET", modulePath, true);
xhr.responseType = "";
xhr.send();
}
<span id="introCurrency" class="introCurrency"><p>Copper standard</p></span>
But, always a but right? But when I go to select part(.introCurrency) of that inserted text using document.getElementById('introCurrency') get an error saying 'introCurrency'[null] it is not an object. But querySelectorAll does locate it and I can work with it, but it is a little fudgey:
var aModule =
document.querySelectorAll('.introCurrency');
for (var i=aModule.length; i--;){
aModule[i].style.display = 'none';
}
I would much rather use document.getElementById. I hope someone can tell me what's going on. Thank you.

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

can xmlhttpRequest response wait even after onload

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.

Read page XML using Javascript

Hey guys, this is driving me absolutely insane so I wanted to ask the experts on this site to see if you know how to do it =)
I'm trying to create some javascript code that can read out elements of a web page (eg. what does the first paragraph say?). Here's what I have so far, but it doesnt work and I cant figure out why:
<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
alert("done loading");
var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
alert(responseDoc.evaluate("//title",responseDoc,null,
XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}
else {
document.write("<error>could not load page</error>");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->
The alert that keeps appearing is "null" and I can't figure out why. Any ideas?
This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/
Update:
Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
//alert("done loading");
//alert(req.responseText);
var responseDoc = new DOMParser();
var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
try{
alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}catch(e){
alert("error");
}
}
else {
document.write("could not load page");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);
I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.

Categories