I have a simple javascript html file that I am using to perform a function that is called from menu item that I added to the Internet Explorer default context menu (through windows registry). The menu click triggers the following javascript:
<script type="text/javascript">
var req = new ActiveXObject("Microsoft.XMLHTTP")
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var serverResponse = req.responseText;
alert(serverResponse); // Shows "15"
}
}
};
req.open("POST", "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey", true)
req.setRequestHeader("Content-Type","application/json")
req.send('{"longUrl": "https://bing.com"}')
</script>
If I run this by opening the html file in IE it works fine. I get the response text. However, if I load it through the Context Menu the "onreadystatechange" function is never called.
If I add "alert("test") to the end of my script the test alert pops up followed a fraction of a second later by the serverResponse alert. I assume it has something to do with the alert blocking or forcing the browser to do something but I can't figure out why it works when loaded as a page but not through the Context menu.
I should note that the rest of the script DOES get called, so I know the menu item is working.
EDIT:
The above code snippet runs and displays an alert dialog containing the text of the response from the server whenever it's executed as an html page. If executed through the context menu I never get the "alert(serverResponse)".
However the following version does work when called from the context menu:
<script type="text/javascript">
var req = new ActiveXObject("Microsoft.XMLHTTP")
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var serverResponse = req.responseText;
alert(serverResponse); // Shows "15"
}
}
};
req.open("POST", "https://www.googleapis.com/urlshortener/v1/url?key=myAPIkey", true)
req.setRequestHeader("Content-Type","application/json")
req.send('{"longUrl": "https://bing.com"}')
alert("test")
</script>
The only difference is the inclusion of the "alert("Test")" line at the end
Related
I would like an element of my html page to be taken from another html file. So, such a widget displayed on many pages at once.
I was able to write JS code so that the content of the element is taken from another file. Code below:
//* Accordion - replace */
var fn = (event) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", '/widgets/accordion.html', true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
document.getElementById("accordion").innerHTML = xhr.responseText;
}
else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null); }
document.addEventListener('DOMContentLoaded', fn, false);
document.addEventListener
The item (accordion) displays correctly, as in the code here:
https://codepen.io/jakub-czeszejko-sochacki/pen/rNWNwrN
But unfortunately it doesn't work properly as if JS code is not being read for this element. As a result, when you click on the accordion button, the accordion does not open.
Is it even possible for this to work with JS?
Problem solved.
It turned out that the JS accordion initiation took place before its html was loaded with the line:
document.getElementById ("accordion"). innerHTML = xhr.responseText;
It was enough to put the initialization code (the accordion opening code) in the function and call this function after the above line of code.
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.
i wanna know can ajax call triggering onload event on the targeted page?
so it's like this, i have one page (test.html) with simple function to change the content of a div that will run when the page load...
here is the code :
<body onLoad = "a()">
<div id="main">the result is here</div>
</body>
<script>
function a()
{
document.getElementById("main").innerHTML =
"Success";
}
</script>
and i have another page (call.html) with ajax call targeted test.html and show the result inside the div...
here is the code :
<body>
<button onclick="call()">Click</button>
<div id="box"></div>
</body>
<script>
function call()
{
var xmlhttp = new XMLHttpRequest();
var url = "test.html";
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box").innerHTML =
xmlhttp.responseText;
alert("Success");
}
}
xmlhttp.send();
}
</script>
if i just simply load the test.html, the content inside div will change, but if i use call.html to call that page, the inside won't change...
is this because ajax doesn't trigger function inside onload event?
This is happening because you are trying to open a URL from local i.e. using file:// and not via HTTP or HTTPS.
This thread can give you a better insight on how to proceed further.
I have two AJAX functions, one links to a file that edits a MYSQL table, and the other loads the new content to a <div>
The function to load the new data is not being fired.
This function links to a page called clear_tasks.php which TRUNCATEs a table in my database.
function clear_tasks(){
var xmlhttp;
if( window.XMLHttpRequest ){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
xmlhttp.open('GET', 'script_files/clear_tasks.php', true);
xmlhttp.send();
}
This next function links to a page called task_info.php which echos a list of all the table entries.
function load_content_from_file( div_id, url ){
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(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
The <div> which should trigger these events looks as follows:
<div onClick="clear_tasks(); load_content_from_file('task_list', 'script_files/task_info.php');">Clear Tasks</div>
The load_content_from_file() function uses two parameters: div_id which is the div into which the content from task_info.php should be loaded, and url which of course is the source file itself (task_info.php)
The load_content_from_file() function is not being fired and I have to refresh the page to see the new content (I use load_content_from_file() in a $(document).ready() function).
How come the load_content_from_file() function is not firing? Ive tried using setInterval() and setTimeout() functions but to no avail.
I have checked your code on my own side. Both functions are 'fired clear_tasks()' and 'load_content_from_file' are firing when I click on 'Clear Tasks'.
The problem may be on your path with 'script_files/task_info.php', Or inside the task_info.php which is supposed to response the data for 'task_list' div.
Because if I return simple text by 'task_info.php', then the text would appended into 'task_list' div smoothly.
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.