Can anyone figure out why this is throwing a syntax error? All of the code looks correct to me.
<script type="text/javascript">
var rootdomain="http://"+window.location.hostname;
function ajaxinclude(url)
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
pagerequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
pagerequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
pagerequest.open('GET', url, false) //get page synchronously
pagerequest.send(null)
writecontent(pagerequest)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || pagerequest.status==200)
document.getElementById("page1").innerHTML = pagerequest.responseText;
}
It's throwing an error on line 7 -- var pagerequest = false;
If you comment it out, it just throws an error on the next line. Any ideas?
Thanks in advance for your help!!
Yopur writecontent is wronge (argument naming) try:
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || page_request.status==200)
document.getElementById("page1").innerHTML = page_request.responseText;
}
Also, there's no real value to this:
var pagerequest = false;
Since you never return it without setting it somewhere else in your code might as well just be:
var pagerequest;
In your writecontent function, you call the argument page_request, but then refer to it in the function body as pagerequest (without the underscore).
Otherwise, your code should be working -- see http://jsfiddle.net/2eynH/ for an example.
First things first - utilize http://jslint.com/
It does not like your writecontent function.
And pagerequest = new XMLHttpRequest() is missing a semicolon.
Also, I also like to "rip" my javascript through YUI Compressor to help reveal syntax errors.
http://developer.yahoo.com/yui/compressor/
Some more missing semicolons:
pagerequest = new ActiveXObject("Msxml2.XMLHTTP")
pagerequest = new ActiveXObject("Microsoft.XMLHTTP")
One more thing. Even though javascript allows you to do something, does not mean that you should. Declaring pagerequest as a boolean, then setting it to an ActiveXObject is a little confusing. I would probably initialize it to null. Then "test" for null later on down in the code.
You are missing semicolons on almost all lines.
Cleaned up code:
function ajaxinclude(url) {
var pagerequest;
if (window.XMLHttpRequest) { // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // if IE
try {
pagerequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
pagerequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (ec) {}
}
}
else {
return false;
}
pagerequest.open('GET', url, false); // get page synchronously
pagerequest.send();
writecontent(pagerequest);
}
function writecontent (page_request) {
if (window.location.href.indexOf("http") == -1 || page_request.status == 200) {
document.getElementById("page1").innerHTML = page_request.responseText;
}
}
Your code is not valid. Semi-colons are added to your code when doesnt have it or it thinks it should have it.
So in
function ajaxinclude(url)
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
the javascript compiler will do the following
function ajaxinclude(url); // note the semi-color meaning the { starts floating in the middle of nowhere
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest();
else if (window.ActiveXObject){ // if IE
try { //and so on
As most people have suggested run JSLint over it to see the mistakes.
Edit from comment
You can see the Semi-colon insertion details in the blog
Related
I am using an AJAX call within a javascript function to populate a SELECT input. This script does not work the first time but works as I intend it to each subsequent time that it is called. The relevant code follows:
function getXMLHttp()
{
var xmlHttp;
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function populateEntries(menu, userName, entryRow)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200) && (xmlHttp.responseText == ""))
{
window.alert("There are no records to view!"); }
else if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200))
{
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "getUsers.php", true)
xmlHttp.send(null);
ADDITIONAL UNRELATED CODE FOLLOWS ....
}
I've checked to see if the "response" is being passed from the AJAX call during the first function call and it is but it is not being passed out of the function for further use in the code that follows except on subsequent function calls. Can anyone tell me why this is happening? Your help will be very much appreciated. Before you tell me that this can be done with jquery, please understand that I need to do it with javascript.
I am using jcaptcha for image verification in my form. Before the form is submitted I make an ajax call using javascript to validate the text entered by the user corresponding to the image displayed. I get the result and update the value of a textbox(imageVerification). After the function that makes this ajax call is executed I pick up the value from this just updated textbox(imageVerification) for the result.
Here is the problem: I am not able to pick up the value from this textbox(imageVerification).
it always shows up as blank.
Catch: if I use an alert() before picking up the value, I am able to pick up the value correctly. I ran this in firebug debug mode and found out that it works in debug mode even without using the alert.
It seemed there is a delay before which the value in the textbox(imageVerification) gets updated. So i introduced a setTimeout() method and was able to pick up the value.
But I dont feel this is the right solution. I am assuming javascript executes sequentially. So why is my statement which is picking up the value after it has been updated by a method not able to get it immediately. Result is even though the image verification is successfull, my check fails since it is not able to pick up the result value from the textbox.
Also, if I use a simple function to update the textbox(imageVerification) instead of a ajax call, I dont face this problem.
Here is the code I am using for the ajax call.
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
req.onreadystatechange = function() {
requestContainerContent(req, containerid);
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(parameterString);
}
function requestContainerContent(req, containerid) {
if (req.readyState == 4 && (req.status==200 || window.location.href.indexOf("http")==-1)){
//document.getElementById(containerid).innerHTML = req.responseText
//document.getElementById(containerid).value=req.responseText;
document.forms['ratingForm'].elements[containerid].value = req.responseText;
}
}
This is the function for image verification:
function validateImage(){
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
fetchContainerContent('captchaController','imageVerification');
var obj = document.forms['ratingForm'].elements['imageVerification'];
//alert('val '+obj.value);
var vall = obj.value;
if(vall=='PASS'){
return true;
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
return false;
}
}
post my call to fetchContainerContent('captchaController','imageVerification'), the value for imageVerification textbox should be set. If I use the alert box which is commented after the fetchContainerContent('captchaController','imageVerification') call it works fine.
Please help me out. Thanks alot
UPDATED ANSWER: Misread program flow on first pass.
The basic problem is you're trying to get an immediate response from the validateImage() function (return true or false) when the XMLHttpRequest needs time to complete.
Move the actions taken based on the return to their own functions (validFunction, invalidFunction) and try this:
function validateImage() {}
if(isBlank(document.forms['ratingForm'].elements['jcaptcha'].value)){
showError('',"Please enter the text seen in the image above",'jcaptchaError');
return false;
}
var obj = document.forms['ratingForm'].elements['imageVerification'];
validReq = fetchContainerContent('captchaController','imageVerification');
validReq.onload = function () {
var validResp = this.reponseText;
if(validResp=='PASS'){
validFunction();
}
else{
showError('',"Image verification failed. Please refresh image and try again","jcaptchaError");
invalidFunction();
}
}
validReq.send(parameterString);
}
function fetchContainerContent(url, containerid) {
var imageValue = document.forms['ratingForm'].elements['jcaptcha'].value;
var req = false;
var parameterString;
if (window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
return false;
}
parameterString = "jcaptcha="+imageValue;
req.open('POST', url, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return req;
}
I'm making a mobile site using Dashcode to help me creating better UIs, but the problem is that I'm getting a strange Parse Error on my code, where nothing is wrong... This is the code:
function get_currency(from, to) {
var XMLHttp; // Create the Ajax handler
XMLHttp = new XMLHttpRequest();
var url = "http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=" + from + to + "=X";
XMLHttp.open("GET", url, true);
XMLHttp.onreadystatechange = function() {
if(XMLHttp.readyState == 4) {
/* Once the server has completed its tasks display the result */
var response = XMLHttp.responseText;
var parsed_reply = response.split(',');
document.getElementById('txtAmount').value = parsed_reply[1];
}
XMLHttp.send(null);
}
function btConvert_Click(event)
{
get_currency("BRL", "USD");
}
The error is occurring(According to the debugger) at the line 209(the last line of the code), which is the } a the end of this code that I gave. What's wrong?
You're missing a closing } for your onreadstatechange handler, causing the parser to puke at the end of the script. Given the indentation, it's the closing } for the if(XMLHttp.readyState...) check
You're missing a }
Based on your spacing, you haven't closed the { from
if(XMLHttp.readyState == 4) {
I'm designing a client side script that will read an XML file and display it, like this:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
function loadXML(xmlFile) {
xmlDoc.async = "false";
xmlDoc.onreadystatechange = verify;
xmlDoc.load(xmlFile);
}
function verify() {
if(xmlDoc.readyState != 4) {
return false;
}
}
function traverse(tree) {
if(tree.hasChildNodes()) {
document.write('<ul><li>');
document.write('<b>' + tree.tagName + ': </b>');
var nodes = tree.childNodes.length;
for(var i = 0; i < tree.childNodes.length; i++) {
traverse(tree.childNodes(i));
}
document.write('</il></ul>');
} else {
document.write(tree.text);
}
}
function initTraverse(file) {
loadXML(file);
var doc = xmlDoc.documentElement;
traverse(doc);
}
When I fired Safari I saw that nothing was displayed, then I've opened the Error Console and what I got was this:
ReferenceError: Can't find variable: ActiveXObject
What should I do to make this work?
PS: I would prefer if this page could be capable of running at Mobile Safari
ActiveXObject do not work outside of internet explorer.
There are a few alternative xml parser's and handlers like E4X. Although E4X is currently only done in firefox (https://developer.mozilla.org/En/E4X/Processing_XML_with_E4X).
If using jQuery is an option then you can look into marcgrabanski.com/articles/jquery-makes-parsing-xml-easy
Some interesting stuff going on there. Most interesting is the async = false line. You probably want to re-consider that bit. In order to change to an asynchronous request, you would have to re-write some other code and remove the document.write calls.
Regardless, here is a (untested but hopefully) drop in replacement for what you have using XMLHttpRequest instead of an xml document.
var xmlDoc = null;
function loadXML(xmlFile) {
var request = new XMLHttpRequest();
request.open('GET', xmlFile, false); // false is synchronous
request.send();
xmlDoc = request.responseXML;
}
You may have to do some debugging...
You should have something cross-browser compatible with either DOMParser or DOMDocument. Of course, I'm not sure if you're wanting to parse a XML URL or a XML string. For a XML URL, I recommend:
if (window.XMLHttpRequest) return new window.XMLHttpRequest();
else if (window.ActiveXObject) {
// the many versions of IE's XML fetchers
var AXOs = [
'MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
'MSXML.XMLHTTP'
];
for (var i = 0; i < AXOs.length; i++) {
try { return new ActiveXObject(AXOs[i]); }
catch() { continue; }
}
return null;
}
For a XML string, this code block would work better:
if (window.DOMParser) return (new DOMParser()).parseFromString(str, 'text/xml');
else if (window.ActiveXObject) {
var doc;
// the many versions of IE's DOM parsers
var AXOs = [
'MSXML2.DOMDocument.6.0',
'MSXML2.DOMDocument.5.0',
'MSXML2.DOMDocument.4.0',
'MSXML2.DOMDocument.3.0',
'MSXML2.DOMDocument',
'Microsoft.XMLDOM',
'MSXML.DOMDocument'
];
for (var i = 0; i < AXOs.length; i++) {
try { doc = new ActiveXObject(AXOs[i]); break; }
catch() { continue; }
}
if (!doc) return createElement('div', null);
if (doc.async) doc.async = false;
doc.loadXML(str);
return doc;
}
return createElement('div', null);
The DOMDocument objects do support a load() method for loading XML from a URL, but it's a different syntax than the XMLHttpRequest and XMLHTTP methods.
The DOMDocument appears (at least from the MSDN docs) to also contain the XMLHTTP methods, so you could interlace DOMDocument in the AXOs array, but I'm not certain about that. Plus, I can't imagine DOMDocument being in place without XMLHTTP.
I am trying to load an XML file using Javascript and I have yet to find a good function that works in IE, Firefox, and Safari. The load function I am currently using is basically the one straight out of the w3schools tutorials:
http://www.w3schools.com/XML/tryit.asp?filename=tryxml_dom_createelement
The exact code looks like:
if (window.ActiveXObject)
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation.createDocument)
{
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
xmlDoc.load(dname);
Where dname = the url of the xml file. This code gets a "TypeError: Value undefined (result of expression xmlDoc.load) is not object." in Safari.
I have also tried the code on this site:
http://developer.apple.com/internet/webcontent/xmlhttpreq.html
However, it yields a null XML file. Can anyone help?
Sounds like the problem is that Safari does not support document.implementation.createDocument as a method to fetch and load XML sources. You must use an XMLHttpRequest to fetch and parse the XML AFAIK.
I've tried a modified version of the code from the Apple tutorial you linked and it seemed to work for me. This code is not the best in the world, and it's missing a lot of error handling, but it's the only proof of concept I had on hand.
Note: I highly recommend using a library. There are browser inconsistencies abound with XMLHttpRequests and XML parsing. It's worth the investment!
For a non library version I used a modified version of the safari code to get the XMLHttpRequest:
function getXHR(url,callback) {
var req = false;
// branch for native XMLHttpRequest object
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
// branch for IE/Windows ActiveX version
} else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
}
if(req) {
req.onreadystatechange = function() { callback( req ) };
req.open("GET", url, true);
req.send("");
}
}
Grabbing the XML from the result is not without its own quirks as well:
function getXML( response ) {
if( response.readyState==4 ) {
//Get the xml document element for IE or firefox
var xml;
if ( response.responseXML ) {
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(response.responseText);
} else {
xml = response.responseXML;
}
return xml;
}
return null;
}
Finally use what you get:
function callback( response ) {
var xmlDoc = getXML( response );
if( xmlDoc ) {
//do your work here
...
}
}
If you still find yourself having trouble there are a few things you can check that will likely solve your problem.
Did you set your content type to text/xml?
Is your request actually making it to the server and back?
When you alert/examine the responseText, do you see anything that does not belong?
Is your XML properly formatted? Run it through a validator.
Best of luck! Cheers.
You might want to look at XML for <Script>. I've seen some posts that indicate that they've solved the problem on Safari with it.