Cannot traverse inside html object - javascript

I'm trying to retrieve page source from the link by http request, and than try to parse it.
Lets assume that I have url;
http://www.biletix.com/search/ISTANBUL/tr#!selectedDate:01/07/16
When I run the following command on the console I get the title as; "Hüsnü Şenlendirici - Taksim Trio"
document.getElementsByClassName("ln1 searchResultEventName")[2].innerText
But the same approach does not work when I try to apply it on the page source that I request.
To get the page source I use;
httpGet("http://www.biletix.com/search/ISTANBUL/tr#!selectedDate:01/07/16",function(result) {
var el = document.createElement('html');
el.innerHTML = result;
//the following code returns undefined
console.log(el.getElementsByClassName("ln1 searchResultEventName")[2].innerText);
});
Why the line console.log(el.getElementsByClassName("ln1 searchResultEventName")[2].innerText); returns undefined? Why I cannot reach as I reach from the console?
httpGet is here;
function httpGet(theUrl, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, true );
xmlhttp.send();
}

Related

Import text file into a WordPress widget using JavaScript

I would like to have a WordPress text widget with a javascript that would populate the widget with text from some .txt file (this is to allow dynamic content on a cached page by allowing me to update that text file with new HTML content).
I found this thread and tried the following code, which did not work:
<script type="text/javascript">
function read(textFile){
var xhr=new XMLHttpRequest;
xhr.open('GET',textFile);
xhr.onload=show;
xhr.send()
}
function show(){
var pre=document.createElement('pre');
pre.textContent=this.response;
document.body.appendChild(pre)
}
read('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
</script>
Any suggestions on how to fix it?
Do you know Javascript or are you just hoping for a copy and paste solution? Perhaps try reworking this code here:
function getStuff(url) {
var xhttp, jsonData, parsedData;
// check that we have access to XMLHttpRequest
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// get the data returned from the request...
jsonData = this.responseText;
// ...and parse it
parsedData = JSON.parse(jsonData);
// return the data here
// if the data you're returning is an object
// you need to know the endpoints
// for example, if there was a username,
// you might return parsedData.username
var something = parsedData.endpoint;
// debug / test
console.log(something);
var elementToShowStuffIn = document.getElementById('theIDOfTheElement');
elementToShowStuffIn.innerHTML = something;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
getStuff('https://raw.githubusercontent.com/Raynos/file-store/master/temp.txt');
Yes, this works. Just replace this line here: var something = parsedData.foo.bar;

Get Date Header Asyncronously

As the title says, I want to get the Response Header Date value, but I keep getting the following warning :
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check https://xhr.spec.whatwg.org/.
My code :
function getxmlhttp () {
// although IE supports the XMLHttpRequest object, but it does not work on local files.
var forceActiveX = (window.ActiveXObject && location.protocol === "file:");
if (window.XMLHttpRequest && !forceActiveX) {
return new XMLHttpRequest();
}else {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
}
alert ("Your browser doesn't support XML handling!");
return null;
};
function srvTime(){
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.open('GET',"blank.php",false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
console.log("raw " + xmlHttp.getResponseHeader("Date"));
return xmlHttp.getResponseHeader("Date");
};
When I switch this line:
xmlHttp.open('GET',"blank.php",true);
To be true, the value returns NULL.
So can this be done, or do I have to just live with the warning in the console?
Thank you
As your title states, you must make the request asynchronously. That means you have to issue the request and wait for it to complete to get the information. Something like this should work:
function srvTime(callback) {
xmlHttp = getxmlhttp();
//xmlHttp.open('HEAD',window.location.href.toString(),false);
//need to send this to a non-volitile page
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { // The operation is complete
console.log("raw " + xmlHttp.getResponseHeader("Date"));
callback(xmlHttp.getResponseHeader("Date"));
xmlHttp = null;
}
};
xmlHttp.open('GET', "blank.php", true);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send(null);
};
Note that you must change the signature of your srvTime method. You can't return the data from it, the caller must supply a callback function that receives the date once the request completes.
An example of how you would use this function with the new signature is as follows:
srvTime(function (serverDate) {
document.getElementById("clock").innerHTML = "Game Time: " + serverDate;
});

Ajax request to load .php file not working

Trying to load contents from postcode.php file into a #postcodeList div, but it is not working (nothing happens). I checked postcode.php file it echoes al correct information.
var loadicecream = document.getElementById("iceCreams");
loadicecream.addEventListener("click", iceAjax, false);
function iceAjax() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","ice-cream-list.php",true);
xmlhttp.send();
document.getElementById("ice-cream-list").innerHTML = xmlhttp.responseText;
}
You want the query to execute asynchronously (the third parameter to open function) and then you synchronously try to read the value. This happens before the query has been sent, so it will always be empty.
Either run the load synchronously, or set the xmlhttp.onreadystatechange to point into a function where you handle the loaded state. The best way is to do it asynchronously since you don't want to block the user from using the page while loading data.
Quick example, only handles the success case:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("postcodeList").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","postcode.php",true);
xmlhttp.send();
Read up on the documentation for the onreadystatechange, at least you want to handle the case where there is a timeout or some error, otherwise the user won't know something went wrong.

AJAX: head and more

For asynchronous quick-checks of an URL, I use AJAX with method=HEAD:
function ajax_quickresponse(url) {
var xmlhttp = null;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject)
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.open("HEAD", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if ((xmlhttp.status > 199 && xmlhttp.status < 400))
; //OK
else
; //ERR
};
};
xmlhttp.send(null);
};
};
This receives is enough for checking the http status, but seems to abort the script at serverside (url). E.g. I can try with a simple php script (url="http://my-host.er/test/script.php") which does sleep(2); and log a success message afterwards.
With xmlhttp.open("HEAD", url, true);, there is no success entry in the log.
With xmlhttp.open("GET", url, true);, there is a success entry in the log.
However, with GET/POST, the javascript is waiting 2 seconds instead of instantly (with HEAD).
The status is known instantly and the javascript does not need to wait for the final response.
How to take advantage of both methods? First, I need the status instantly, as soon as the header comes in, and after the external url/script returns, then i'd like another listener.
E.g. first alert('http status='+xmlhttp.status); and maybe delayed, depending on the url/script, alert('finally completed');
Do you have a tip how to achieve this with one single call?

No response when using AJAX and JSON

function getIDs() {
alert("1");
var title = document.getElementById('title').value;
alert(title);
title = "http://www.imdbapi.com/?i=&t=" + title;
alert(title);
xmlhttp=new XMLHttpRequest();
alert("2");
xmlhttp.open("GET",title,true);
alert("3");
xmlhttp.send();
alert("4");
var imdbData = xmlhttp.responseText;
alert(imdbData);
var imdbJSON = JSON.parse(imdbData);
//document.getElementById('title').value = imdbJSON.Title;
alert(imdbJSON.Title);
document.getElementById('imdbid').value = imdbJSON.ID;
return true;
}
I'm trying to fetch the ID of a film based upon it's title, the function gets called successfully and the alerts are correct until the alert which returns "imdbData", which returns a blank alert, then no more alerts occur, I'm unsure where I'm going wrong here. Any assistance would be appreciated.
You're opening it asynchronously. To make it synchronous, change this:
xmlhttp.open("GET",title,true);
To this:
xmlhttp.open("GET",title,false);
A usually-considered-better way would be to make it work with asynchronicity:
function getIDs() {
alert("1");
var title = document.getElementById('title').value;
title = "http://www.imdbapi.com/?i=&t=" + title;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
var imdbData = xmlhttp.responseText;
var imdbJSON = JSON.parse(imdbData);
document.getElementById('title').value = imdbJSON.Title;
document.getElementById('imdbid').value = imdbJSON.ID;
}
};
xmlhttp.open("GET",title,true);
xmlhttp.send();
return true;
}
Additionally, you cannot request pages from other domains. You may need to switch to JSONP if the API you're using supports it, or use your web server as a proxy.
You are not allowed to do cross site scripting with JavaScript which is why you get nothing in return.
You need to be on the same domain as you post your AJAX call to.
Use a serverside script to parse the URL for you instead.

Categories