Javascript not executing procedures correctly - javascript

I'm trying to use JavaScript to manipulate page content in a dummy webpage I'm building.
To that end, I wrote a little function called writeText(file_name, location) that gets a HTML file specified by the file name, and prints the content of that file to the innerHTML of a pair of <div> tags whose id attribute correspond to the location field.
I then wrapped the calls in other functions to automate building full pages like this.
So I call something that looks like this:
function displayHome() {
writeText('homeMain.html', 'mainFrame');
writeText('homeSide.html', 'sideFrame');
}
...to display the home page.
However, when I call this function, the display only updates the 'sideFrame' object and doesn't make any changes to the content of 'mainFrame'. But if I interrupt the function with an alert("Dummy") between the two writeText() calls, then both of the contentFrames update correctly.
I was wondering if anyone has seen anything like this before, and if anyone knows how to fix it.
For completeness' sake (this was copied nearly verbatim from the w3schools website):
function writeText(script_file, location) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
document.getElementById(location).innerHTML = xmlhttp.responseText;
}
xmlhttp.open("GET",script_file,true);
xmlhttp.send();
}

You are using a global variable xmlhttp, so it gets clobbered the 2nd time the function runs. The request itself is asynchronous, so the second call runs while the first one is still running.
To fix this, use a local variable instead (so each call to the function has its own xmlhttp) by using the "var" keyword before xmlhttp:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

Related

Function delivers value, before ajax request changed it

I am running an ajax request to retrieve a value of either 0,1, or 2 based upon some mysql code in the "check_answer_status.php" file. For test purposes, I have included the alert to check whether the general ajax and mysql request works fine and it does, hence the value contained within "Questiions.answerStatus" at the time of the alert is correct. However, my problem is that the function "checkAnswerStatus" has already executed and did not change the inital value of "answerStatus" (which I set to 50 for test purposes).
Context: sometime later in the code I want to execute code dependent on the value of the variable "answerStatus".
I believe I need to somehow include something like an "oncomplete" or something comparable, but I do not know how to do that. Can anyone help me out? Many thanks!
var = Questions = {
answerStatus:50,
checkAnswerStatus : function(question){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
alert(Questions.answerStatus);
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
},
The request you make is asynchronus (the third parameter of the xmlhttp.open function). If you changed it to:
xmlhttp.open("POST","../../include/check_answer_status.php",false);
it should work.
Another options is to pass a callback to your checkAnswerStatus function, and call the callback when the request finishes. Example:
checkAnswerStatus : function(question, callback){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
callback(Questions.answerStatus); //call the function
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
}
and then you will call the function like this:
Questions.checkAnswerStatus("bla bla", function(answerStatus) {
alert(answerStatus);
});
in addition to Nemos answer I would recommend you read following resources from MDN:
More technical API documentation for a brief overview of all the possibilities:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
More real life usecases:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Hope this helps

Load specific element from another page with vanilla js

I've this function to make an ajax request:
I want to replace content in
var dialog_body = document.querySelector('#dialog .body')
in page1.php with the content of
page2.php#load
that is located in
var href = 'page2.php'
.......
function load(div_where_change, url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
div_where_change.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
load(dialog_body, ref+'#load');
And It doesn't work..
My final process is similar to jquery load, but I wanna use only vanilla js and I've not found any documentation or article for load only one element of another page, but only full page load......
Please help me..
function getPage(url, from, to) {
var cached=sessionStorage[url];
if(!from){from="body";} // default to grabbing body tag
if(to && to.split){to=document.querySelector(to);} // a string TO turns into an element
if(!to){to=document.querySelector(from);} // default re-using the source elm as the target elm
if(cached){return to.innerHTML=cached;} // cache responses for instant re-use re-use
var XHRt = new XMLHttpRequest; // new ajax
XHRt.responseType='document'; // ajax2 context and onload() event
XHRt.onload= function() { sessionStorage[url]=to.innerHTML= XHRt.response.querySelector(from).innerHTML;};
XHRt.open("GET", url, true);
XHRt.send();
return XHRt;
}
arguments:
getPage(
URL : Location of remote resource ,
FROM : CSS selector of source tag on remote page ,
TO: CSS selector of destination tag
)
EX 1. (typical use) virtually grab the next page:
when on http://www.codingforums.com/forumdisplay.php?f=2
show table from http://www.codingforums.com/forumdisplay.php?f=2&order=desc&page=2
getPage("/forumdisplay.php?f=2&order=desc&page=2",
"#inlinemodform",
"#inlinemodform" );
notice how "#inlinemodform" is repeated? It's moving the same block to the same block on another page.
You can omit the 2nd CSS selector when it's a duplicate, so the following is 100% equivalent to the above:
getPage("/forumdisplay.php?f=2&order=desc&page=2",
"#inlinemodform" );
EX 2. (defaults) replace this whole page with another post :
getPage("http://www.codingforums.com/showthread.php?t=281163")
EX 3. (external content) inject event listings from UIUC into the current page:
getPage("//www.it.illinois.edu/news/", ".list.events.vcard.clearfix", ".tcat" )
one difference from $.load() is that script tags on the remote page are not executed, which i rather like. Prototype.js has a good script-tag-finding regexp that you can use to eval inline scripts, and you can re-add the urls of any .src-based scripts if you need all that functionality. I also cache the fetch in sessionStorage, so if your external content rotates or updates, use a random query param or remove the sessionStorage check by changing the 2nd line to var cached="";
EDIT: fixed a really dumb bug i created when renaming the variables for public readability; forgetting one.

Calling multiple perl scripts over APACHE server?

I am pretty new to creating web applications, so I am very unfamiliar with working over a web server. Just to let everyone know, I am implementing html, javascript, strawberry perl, AJAX, and running over an APACHE 2 web server. I finally have my web app working, I have an html file that calls a perl script that is in my htdocs directory. Here is a mock up of my .html file for reference, this one simply alerts the user of the output printed by the perl script:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var str;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Get output from perl script and print it
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open("GET","http://localhost/try.pl" , false); //perl script
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">Display</button>
</body>
</html>
So this file test.html calls a perl script [try.pl] within the same directory. Also, the perl script just prints a number so this alerts the user of the number. This is just an example of my implementation. My actual perl script and java script [inside the ready state block] is much more complicated. Now I have to add functionality to my web app, so to my questions:
I am looking to run a second and separate perl script when a different event happens. For example, when a button is clicked this perl script is being ran. I am going to have another different event, say a double click on an icon or something, that will need to call this second perl script. Will I simply have the new event call a different function [the first is called Loadxmldoc()] that is almost identical to the one I have here except it will have different code in the ready state block and call a different perl script at the end of it? I am a little confused as to how to implement this.
Also, If I have a list of file names within my javascript code, I need to process EACH of the files using a perl script. Currently I am only processing one so calling the perl script as I have here is fine. I have looked all over the internet to try to find how I would do this but it seems every explanation just covers how to call "a" CGI script. So within my code, say where I am "alerting" the user, I am going to have an array that stores the file names. I need to iterate over this array and for each filename [array element] I need to call the same perl script to process that file. How should I go about implementing this? Currently, my html file is only calling the perl script once and I do not know how I could call it for EACH file since my GET command is outside of my ready state block...
Any help or direction would be appreciated. I am expected to deliver soon and have been spending way too much time sifting through repetitive examples that haven't helped me...:/
As far as generalizing your AJAX request, you can create a function (or rather, a set of functions) that would process different types of responses, as follows:
var requests = [];
requests['script1'] = "http://localhost/try.pl";
requests['script2'] = "http://localhost/try2.pl";
var response_processing = [];
response_processing['script1'] = function (xmlhttp) {
var str = xmlhttp.responseText;
alert(str);
};
// Here, you can add more functions to do response processing for other AJAX calls,
under different map keys.
Now, in your AJAX code, you call an appropriate request AND appropriate response processor, based on your script name (passed to loadXMLDoc() call as follows): loadXMLDoc("script1");
function loadXMLDoc(script_name) {
// Your generic AJAX code as you already implemented
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
response_processing[script_name](xmlhttp);
// Careful so script_name doesn't get closured in onreadystatechange()
}
}
xmlhttp.open("GET", requests[script_name], false); //perl script
xmlhttp.send();
}

beginner question: using open method does not load my text file

server: apache http server 2.2
problem: code does not load my text file
hello people. im currently trying to learn javascript and am following several tutorials. written below is a code off of w3schools. what its supposed to do is change the displayed text upon clicking the button. however, this does not work for me. the html file where the code below is save and the text file im trying to open are in the same folder.
im accessing the html file off of chrome using this: http://localhost/ajaxtutorial.html. while it does display the html file correctly, upon clicking the button nothing happens. ive tried changing the file to php and making an equivalent php file to the said text file but still nothing happens. please help.
<html>
<script type="text/javascript">
//comments are from http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
function loadXMLDoc(url , cfunc)
{
var xmlhttp;
//XMLHttpRequest object is used to exchange data with a server behind the scenes
//creates an xmlhttprequest object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//The XMLHttpRequest object has a special property called onreadystatechange
//onreadystatechange stores the function that will process the response from the server
//every time the "ready state" changes, this function will be executed
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function myFunction()
{
loadXMLDoc
("ajax_info.txt",
function()
{
//The XMLHttpRequest object has another property called readyState
//This is where the status of our SERVER'S RESPONSE is stored
//The SERVER RESPONSE can be processing, downloading or completed
//When the property readyState is 4 that means the response is complete and we can get our data
//Download worked as intended, data request successful if status property = 200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
);
}
</script>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
In myFunction the xmlhttp variable is not in the scope of the function. This should be causing a JavaScript error, which you can view in Chrome by going to Menu > Tools > JavaScript console. One way to fix this would be to pass the xmlhttp object as a parameter.
function loadXMLDoc(url , cfunc) {
//some code...
xmlhttp.onreadystatechange=function() {
//pass xmlhttp as a parameter to this function and preserve the context
//see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
cfunc.call(this, xmlhttp);
}
//some more code...
}
function myFunction() {
loadXMLDoc("ajax_info.txt", function(xmlhttp) {
//xmlhttp is now in scope because we passed it as a parameter
});
}
Update
I created a working example at http://jsfiddle.net/6rPgE/
As for your question about the modifications I suggested...
The second parameter to the loadXMLDoc method (cfunc) is a function. In this case, an anonymous function is created inside myFunction which will be passed as the cfunc parameter to loadXMLDoc. When the onreadystatechange callback is invoked, the cfunc function is called with xmlhttp as the first parameter. This parameter is passed into the anonymous function defined inside myFunction, and is responsible for actually doing something with the AJAX response. On an entirely different note, I highly recommend using a debugger (Chrome has one built-in) and the information provided by the browser's error console to assist you in debugging these issues in the future. Learning how to use a debugger will save you countless hours of banging your head against the wall.
Update 2
Just thought it would be nice to look at how this can be done using jQuery with quite a bit less code. AJAX is one area where it can be really nice to use a library that abstracts away the details.
Another example that uses jQuery at http://jsfiddle.net/j9QvE/1/
Update 3
Note that in my code I replaced the path to ajax_info.txt with a path specifically used for testing AJAX functionality in jsFiddle (/echo/js/?js=Success!). This was necessary because ajax_info.txt does not exist on the jsFiddle servers, so requesting it would have resulted in a 404 error. Don't forget to change the path to point to an appropriate resource on your own domain.

Javascript asynchronous calls stepping on one another

I'm using AHAH (as outlined here http://microformats.org/wiki/rest/ahah) to make two calls to populate HTML on a page. The calls happen after the document is ready and are fired off one after another. The result, every time, is the first call gets overwritten with the last calls response. So I'll have two of the same chunks of HTML on the page instead of two unique pieces of code. Sometimes the first call doesn't even get to evaluate it's call back and thus remains empty.
Any ideas?
If you're using the exact code on that page, it's not surprising, as the example there uses a single global variable to store the XMLHttpRequest being made. So there's no way it can work for more than one simultaneous request: calling the function a second time overwrites the req with a new one, causing the req read by ahahDone to be the wrong request.
If you want to allow this you'll have to make req a local variable (by declaring it var in function ahah()), and pass it with the target to the ahahDone() function. Or just do it inline:
function Element_loadHTML(element, url) {
var req= null;
if (window.XMLHttpRequest) {
req= new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
req= new ActiveXObject('MSXML2.XMLHttpRequest');
} catch() {}
}
if (!req) {
element.innerHTML= 'Browser does not support XMLHttpRequest';
return;
}
element.innerHTML= 'Loading...';
req.onreadystatechange= function() {
if (req.readyState===4)
element.innerHTML= req.status===200? req.responseText : 'Error '+req.status;
};
req.open('GET', url);
req.send(null);
}
Element_loadHTML(document.getElementById('appdata'), 'appdata.part.html');
Element_loadHTML(document.getElementById('foo'), 'bar.part.html');
The stuff with the browser sniffing and trying to execute script tags is hopeless and broken; don't use it. It's not good practice to be loading <script> element content into the page.

Categories

Resources