JavaScript - At Wit's End - Simple Ajax Readystate Isn't Working
Hi. Just started fooling around with Ajax a bit back. So far, it's been fine. Today, though, I'm hitting some error I can't figure out. It *should* work, but it doesn't, and I have no idea why.
Simple HTML form page with a bit of css. No big deal. Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <script type="text/javascript" src="livesearch.js"></script> <style type="text/css"> #livesearch { margin:0px; width:194px; } #txt1 { margin:0px; } </style> </head> <body> <form> <input type="text" id="txt1" size="30" onkeyup="showResult(this.value)" /> <div id="livesearch"></div> </form>type </body> </html> Problem area below in bold. Code: function showResult(str){ if (str.length == 0) { document.getElementById("livesearch").innerHTML = ""; document.getElementById("livesearch").style.border = "0px"; } var xmlhttp = getXMLHttpObject(); if (xmlhttp == null){ alert("Your browser does not support XML HTTP requests!"); return; } var url = "livesearch.php"; url = url + "?q=" + str; url = url + "&sid="+Math.random(); xmlhttp.onreadystatechange=stateChanged ; xmlhttp.open("GET", url, true); xmlhttp.send(null); } function stateChanged(){ if (xmlhttp.readyState == 4){ alert("Never seems to hit a readystate==4"); document.getElementById("livesearch").innerhtml = xmlhttp.responseText; document.getElementById("livesearch").style.border="1px solid #A5ACB2"; } } function getXMLHttpObject(){ //Current browsers if (window.XMLHttpRequest){ return new XMLHttpRequest(); } //For IE 5/6 if(window.ActiveXObject){ return new ActiveXObject("Microsoft.XMLHTTP"); } else { return null; } } My PHP file is just a simple echo statement to see that it works to that point. It doesn't. For whatever reason, it never seems to hit readyState ==4. It enters the function (I've checked with alerts), but the if statement never comes out to be true. I have no idea why. I've combed over the code for errors for a while now and I can't find anything. Any ideas? Would be much obliged. Similar TutorialsI needed to know if a remote Page was completely loaded in an iframe. If I try to use framename.contentDocument.readyState=='complete' I get an permissions error. However if a create a local Page such as: ----------------------------------------------- <html> <body> <iframe src="http//:somewhere.com" > </iframe> </body> </html> --------------------------------------- I can check whether the local Page, hence the remote Page I was interested in is loaded. Will this hack go away or does it conform to the standard? This form retrieves results from a mysql database. It works fine but when I click submit it shows the result only for a second. When I hold down submit the result stays there. How do I get the result to stay on the screen after I hit submit? Even better how do I get it to spit out results without having to hit a submit button or press enter? Code: <html> <head> <script type="text/javascript"> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } 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) { document.getElementById("getSpecs").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","getspecs.php?model="+str,true); xmlhttp.send(); } </script> </head> <body> <form> Model: <input onchange="showUser(this.value)" /> <input type="submit" value="Submit" /> </form> <br /> <div id="getSpecs"><b>Product info listed here.</b></div> </body> </html> hi, I had a doubt... here is a simple ajax program to return the length of the string entered in the input html: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type='text/javascript' src="grade.js" > </script> <title>Untitled Document</title> </head> <body> <form action="fallbackpage.php" method="post"> <p>Welcome, student. Please enter your essay he </p> <p> <textarea name="essay" id="essay"> </textarea> </p> <p> <input type="submit" name="submit" value="Submit" onclick=" grade(this.form.essay.value);" /> </p> </form> </body> </html> Java script Code: // JavaScript Document function grade(essay) { // Mozilla version if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } // IE version else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } essay=encodeURIComponent(essay); xhr.open("POST","grade.php"); xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay); xhr.onreadystatechange=function() { if (xhr.readyState==4) { grade = xhr.responseText; alert(grade); } } } php: PHP Code: <?php function grade_essay($essay) { return strlen($essay); } $essay = urldecode(implode(file('php://input'))); $grade = grade_essay($essay); echo $grade; ?> I just use an alert box to alert the length. The script works properly ONLY when the AJAX request is able to outrace the submit request.... which doesnt happen. I have included the action="" part as a fallback option incase JS is disabled What am i doing wrong here? I am learning JS now in the free time... Also i did notice this... when i change the submit button in html to the following code i get 2 alert box..1st one's undefined(i know why) but second one's i will get proper answer Quote: <input type="submit" name="submit" value="Submit" onclick="alert(grade(this.form.essay.value));" /> PS: This is a tutorial here http://www.webmonkey.com/2010/02/aja...ners/#more-775 Code: function addEvent(elem,type,func) { var obj = document.getElementById(elem); if(window.addEventListener) { obj.addEventListener(type,func,false); } if(window.attachEvent) { obj.attachEvent('on'+type,func); } } function $e(obj) { if(obj) obj = document.getElementById(obj); if(!obj) return; return obj; } function homeFunc() { $e('home-wrapper').innerHTML = "<div id=\"choose-container\"><span class=\"choose-buttons\" onclick=\"loginFunc()\">Login Exisiting Account</span><span class=\"choose-buttons\" id=\"createAcct\">Create An New Account</span><span class=\"choose-buttons-highscores\" id=\"createAcct\">Highscores Table</span>"; } function loginFunc() { $e('home-wrapper').innerHTML = "<div id=\"login-container\"><div id=\"error-field\"></div><form method=\"post\" onsubmit=\"return validate_login()\" action=\"./index.php\"><label for=\"username\">Username</label><input name=\"username\" id=\"username\" class=\"input\" type=\"text\" /> <label for=\"password\">Password</label><input name=\"password\" id=\"password\" class=\"input\" type=\"password\" /><input name=\"login\" type=\"submit\" value=\"Login\" class=\"loginButtonClass\" /><div id=\"loginQuickLinks\"><span class=\"loginQuickLinks\" onclick=\"homeFunc()\">Register</span> - <span class=\"loginQuickLinks\">Forgot password?</span></form></div></div>"; } function createAcct() { alert("Create An Account"); } function validate_usr() { var usr = $e('username'); var pwd = $e('password'); if(usr.value.length <= 0 && pwd.value.length <= 0) { loginErrorMsg('Please supply a username and password.'); return false; } if(usr.value.length >= 1 && pwd.value.length <= 0) { loginErrorMsg('Please supply a password.'); return false; } if(pwd.value.length >= 5 && usr.value.length <= 0) { loginErrorMsg('Please supply a username.'); return false; } if(pwd.value.length < 5) { loginErrorMsg('Invalid username or password.'); return false; } if(usr.value.length >= 1 && pwd.value.length >= 5) { $e('error-field').style.cssText='display:block;'; $e('error-field').innerHTML = "<img src=\"/images/ajax-loader.gif\" /> <span style=\"color:#ffffff\">Loading...</span>"; var req; var params = 'user='+encodeURIComponent(usr.value.toLowerCase())+'&pass='+encodeURIComponent(pwd.value.toLowerCase()); if(window.XMLHttpRequest) { req = new XMLHttpRequest(); } if(window.ActiveXObject) { req = new ActiveXObject("Msxml2.XMLHTTP" || "Microsoft.XMLHTTP"); } req.open('POST','server/userChck.php',true); req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); req.send(params); req.onreadystatechange = req; if(req.readyState == 4 && req.status == 200) { if(req.responseText == 0) { window.scrollTo(0,1); setTimeout(function(){loginErrorMsg('Invalid username or password');},1000); return false; } } } return true; } function loginErrorMsg(msg) { window.scrollTo(0,1); $e('error-field').innerHTML = msg; $e('error-field').style.cssText='display:block'; } function validate_login() { var isTurn = (!validate_usr()) ? false : true; return isTurn; } window.onload = function() { setTimeout(function(){window.scrollTo(0,1);},100); addEvent('loginButton','click',loginFunc); addEvent('createAcct','click',homeFunc); } This code works fine when I set this line to false Code: req.open('POST','server/userChck.php',false); but as soon as I set this to true. I doesn't work.... What am I doing wrong here? i have made one page this is page link http://pickthefights.com/fantansy-fi...482&page=fight the code of this page is this <script type="text/javascript"> //////////////////////////////// // // Refreshing the DIV FANBOO2 // //////////////////////////////// function refreshdiv_fanboo2(){ // Customise those settings var seconds = 1; var divid = "fanboo2"; var url = "http://pickthefights.com/fanboo2/?id=<?php echo $idvar ?>"; // Create xmlHttp var xmlHttp_two = AJAX(); // No cache var timestamp = fetch_unix_timestamp(); var nocacheurl = url+"?t="+timestamp; // The code... xmlHttp_two.onreadystatechange=function(){ if(xmlHttp_two.readyState==4){ document.getElementById(divid).innerHTML=xmlHttp_two.responseText; setTimeout('refreshdiv_fanboo2()',seconds*1000); } } xmlHttp_two.open("GET",nocacheurl,true); xmlHttp_two.send(null); } // Start the refreshing process window.onload = function startrefresh(){ setTimeout('refreshdiv_fanboo2()',seconds*1000); } </script> <script type="text/javascript"> refreshdiv_fanboo2(); </script> <div name="fanboo2" id="fanboo2"></div> now what ever i put in fanboo2 page it works fine but javascript or jquery is not working here is code of fanboo2 page, you can check page here http://pickthefights.com/fanboo2/?id=482# here is it is working but not here http://pickthefights.com/fantansy-fi...482&page=fight </script> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script src="http://bxslider.com/sites/default/files/jquery.bxSlider.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $('#slider1').bxSlider(); }); </script> <ul id="slider1"> <li>Slide one content</li> <li>Slide two content</li> <li>Slide three content</li> <li>And so on...</li> </ul> please help me out i want to make java script work on both of this page I have a page that has a simple AJAX call that works fine in firefox and chrome but not in ie. In IE my loading image shows up but the actual sourceURL never loads or shows. Below is my html and javascript code. Can anyone help me with this? <div id="design_strap" style="display:none"> <a href="javascript:loadContent('#content', 'strap.html');">Link</a> <div id="content"></div> </div> <script type="text/javascript"> $.ajaxSetup ({ // Disable caching of AJAX responses cache: false }); function loadContent(elementSelector, sourceUrl) { $(""+elementSelector+"").html('<p><img src="images/loading.gif" width="150" height="150" /></p>'); $(""+elementSelector+"").load(""+sourceUrl+""); //$("content").height(350); } </script> In IE online.php script was executed once, In Firefox didn't worked at all... Where is the problem? Here is my AJAX script: PHP Code: <script language="javascript" type="text/javascript"> <!-- // Get the HTTP Object function gethttpObject2(){ if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else { alert("Your browser does not support AJAX."); return null; } } // Change the value of the outputText field function setOutput(){ if(httpObject2.readyState == 4){ document.getElementById('online').innerHTML = httpObject2.responseText; } } // Implement business logic function doWork(){ httpObject2 = gethttpObject2(); if (httpObject2 != null) { httpObject2.open("GET", "../content/tables/tb_online.php", true); httpObject2.send(null); httpObject2.onreadystatechange = setOutput; } } setInterval(doWork, 10); var httpObject2 = null; //--> </script> <div id='online' ></div> Hi, I'm trying to work through a head first book on ajax and javascript. I am also trying to emplement some of the codes in a small application I had built strictly with server side code. What it does is: two input fields for user defined values. Once the user inputs the two values, they are passed to the action page, some simple math is performed on these 2 values, and then 4 different resluts are displayed back on the action page. What I wanted was of course to make this asynchronous and display the results without a page reload. So, when I reworked the book code for my own use, and try to run the application, I get an error saying my url variable is undefined. The value of the first input seems to be passed though. One thing of note to mention is the application was written in coldfusion. The form values are passed using cf. Not sure if that matters. I mean cf works well with js and ajax, but maybe my original procedure doesnt work with my js code as it is now. Here is the javascript/ajax code: PHP Code: <script type="text/javascript" language="javascript"> var request = null; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxm12.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = null; } } if(request == null) alert("Error creating request object!"); } function getLampVolts() { var lamp = document.getElementById("lampVoltage").value; var url = "calculatorAction.cfm?lamp = " + escape(lampVolts); request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); } function updatePage() { if(request.readyState == 4) { if(request.status == 200) { var lumens = request.responseText; document.getElementById("lumens").value = lumens; } else alert("Error! Request Status is " + request.status); } } </script> Here is the form: Code: <form action="calculatorAction.cfm"> <table> <tr> <th>Lamp Voltage</th> <td><input name="lampVoltage" id="lampVoltage" type="text" /></td> </tr> <tr> <th>Socket Voltage</th> <td><input name="socketVoltage" id="socketVoltage" type="text" /></td> </tr> <tr> <td><input type="button" value="Submit" onClick="getLampVolts();" /></td> <td><input type="reset" value="Reset" /></td> </tr> </table> and here is my action page calculatorAction.cfm: Code: <cfparam name="bulbCalculator.cfm" type="any" default="0"> <!--- Set User Defined Values of Form ---> <cfset lampVolts = FORM.lampVoltage> <cfset actualVolts = FORM.socketVoltage> <!--- Set Constants For Calculations ---> <cfset lumens = 27500> <cfset life = 500> <cfset watts = 65> <cfset colorTemp = 3500> <!--- Perform Calculations ---> <cfset actualLumens = ((actualVolts/lampVolts)^3.4)*lumens> <cfset lumenPercent = actualLumens/lumens*100> <cfset hours = ((lampVolts/actualVolts)^13)*life> <cfset hourPercent = hours/life*100> <cfset actualWatts = ((actualVolts/lampVolts)^1.3)*watts> <cfset wattPercent = actualWatts/watts*100> <cfset temperature = ((actualVolts/lampVolts)^.42)*colorTemp> <cfset tempReduction = temperature-colorTemp> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <cfsavecontent variable="calculations"> <table> <cfoutput> <tr> <td>Lamp Rated Voltage:</td> <td>#lampVolts#</td> </tr> <tr> <td>Socket Application Voltage:</td> <td>#actualVolts#</td> </tr> <tr> <td id="lumens">Percent of Lumens Used:</td> <td>#round(lumenPercent)#%</td> </tr> <tr> <td>New Rated life in Percentages:</td> <td>#round(hourPercent)#%</td> </tr> <tr> <td>Percent of Watts Used:</td> <td>#round(wattPercent)#%</td> </tr> <tr> <td>Change in Temperatu </td> <td>#round(tempReduction)#°</td> </tr> </cfoutput> </table></cfsavecontent> </body> </html> Again, the url variable says it is undefined. But the variable "lamp" contains the form field value. Thanks for any help and tips in advance! ** sorry for posting this here. Kinda rushed on time, hoping for some clues. Hello, I am using this code: using prototype too. Code: Code: var haveData = false; [xmllink1, xmllink2, xmllink3].each(function(xmlURL){ if(haveData == false){ new Ajax.Request( xmlURL, { method: 'get', contentType: "application/xml", onSuccess: function( transport ) { var titles = transport.responseXML.getElementsByTagName( 'titles' ); DO SOME WORK HERE haveData = true; throw $break; } }, onFailu function() { return; }, onException: function(request,error) { return; } } What I am trying to do is if my first item "xmllink1" has some data, we break out and end it and now we can 'build some structures' ie.. onSuccess If xmllink1 doesn't have any valid data, we go to xmllink2 etc.. and so forth. Basically, when I get some valid returns.. I want to then exit out of the loop and then act on my data. But I need it in order so I know that my xmllink1 is not being in a race conditiona with xmllink2 etc.. But what is happening is I have simulataneous things going on and I get an onException (because one of the links doesn't resolve or has bad data) and that ends up killing my javascript. How can I test in order.. if link1 is good, great.. exit the "each method" and act on that data.. if xmllink1 is bad (onfairlure or onexception) lets go to xmllink2 etc.... any ideas? Could somebody help me please to explain what I'm doing wrong.... a have this html file with references to some javascripts (datagrid from http://www.datatables.net) and this html file work ok..I mean javascripts a css styling works with table... but when I call this page by ajax and callback (this html page) is forward back into another div , table doesn't work ....just data from page but now functionality from javascript and css styling... how should I force callback result to use javascript and css? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html><head> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico"> <link rel="alternate" type="application/rss+xml" title="RSS 2.0" href="http://www.datatables.net/rss.xml"> <style type="text/css" media="screen"> @import "media/css/demo_page.css"; @import "media/css/demo_table.css"; @import "http://www.datatables.net/media/css/site_jui.ccss"; @import "media/css/demo_table_jui.css"; @import "media/css/themes/base/jquery-ui.css"; @import "media/css/themes/smoothness/jquery-ui-1.7.2.custom.css"; /* * Override styles needed due to the mix of three different CSS sources! For proper examples * please see the themes example in the 'Examples' section of this site */ .dataTables_info { padding-top: 0; } .dataTables_paginate { padding-top: 0; } .css_right { float: right; } #example_wrapper .fg-toolbar { font-size: 0.8em } #theme_links span { float: left; padding: 2px 10px; } </style> <script type="text/javascript" src="media/js/complete.js"></script> <script src="media/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script> <script type="text/javascript" src="media/js/jquery.dataTables.editable.js"></script> <script src="media/js/jquery.jeditable.js" type="text/javascript"></script> <script src="media/js/jquery-ui.js" type="text/javascript"></script> <script src="media/js/jquery.validate.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready( function () { $('#example').dataTable().makeEditable({ sUpdateURL: "update.php", sDeleteURL: "delete.php" }); } ); </script> </head> <body id="index" class="grid_2_3"> <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> <thead> <tr> <th> ID</th> <th> user</th> <th> password</th> <th> first</th> <th> last</th> <th> company</th> </tr> </thead> <tbody> <tr class="even_gradeA" id="1"> <td> 1 </td> <td> XY </td> <td> passwoed </td> <td> Ja </td> <td> jajovic </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="2"> <td> 2 </td> <td> jojo </td> <td> fa25af5301e2dda1fddea740200aa10ab6c70d86 </td> <td> jojo </td> <td> jojovicko </td> <td> 2 </td> </tr> <tr class="even_gradeA" id="3"> <td> 3 </td> <td> kuk </td> <td> d588aebb93e3adf70eac1fb479d6d53f9dc21816 </td> <td> kuk </td> <td> kukovic </td> <td> 3 </td> </tr> <tr class="even_gradeA" id="10"> <td> 10 </td> <td> admin </td> <td> f865b53623b121fd34ee5426c792e5c33af8c227 </td> <td> admin </td> <td> adminovic </td> <td> 3 </td> </tr> </tbody> </table><button id="btnDeleteRow">Delete</button> </body> </html> hi, When I navigate to a page with Ajax on my iphone or ipad, it doesn't show up, page is just blank, I have checked for errors and there is no errors?! here is my Ajax code Code: function datecheckFunction(){ var datecheckRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari datecheckRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ datecheckRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ datecheckRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server datecheckRequest.onreadystatechange = function(){ if(datecheckRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = datecheckRequest.responseText; } } var datepicker = document.getElementById('datepicker').value; var queryString = "?datepicker=" + datepicker; //Add the following line datecheckRequest.open("GET", "http://www.affordableappliancerepairs.co.uk/admin/checkdate.php" + queryString, true); datecheckRequest.send(null); } Can somebody help me to find the problem with the below given code, its not working. $(document).on('keyup', ".add_commi", function() { typingTimer = setTimeout(doneTyping, doneTypingInterval); var pro = $(this).attr('id'); var selectvalue = $(this).html(); var id = pro.slice(-2); var amount = $('#amount'+id).html(); var rate = $('#v_rate'+id).html(); //alert('working'); var data = 'cur_amount='+cur_amount +'&cur_rate='+cur_rate+'&commision='+selectvalue; $.ajax({ type: "POST", dataType: "json", url: "http://localhost/agent/buy-currency-calculations/", data: data, success: function(output){ var cus_rate = output.cus_rate; var total = output.total; var tot_commision = output.commision; alert(cus_rate, total, tot_commision); $('#curr_rate'+id).html(cus_rate); $('#tot'+id).html(total); $('#tot_commi'+id).html(tot_commision); } }); return false; }); Reply With Quote 01-09-2015, 02:53 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts cur_amount, cur_rate and selectvalue are supposedly primitive values (like numbers) but you fetch them as HTML code which the interpreting server script certainly can’t process. (if it should be indeed primitives, you should rather consider using form elements for that). despite that jQuery has a method to fetch values off a form, which might be easier to implement, but that depends on the used HTML code. additionally, in your browser’s dev tools you can check the network pane for what values are sent/received in the AJAX call. It works in Google Chrome but not Firefox and Internet Explorer. My computer has blocked Opera and I don't know how to change that. Too much energy to investigate now, I'll do so later. Are there any pros that can tell me why this is happening? I'm assuming GoogleChrome is fixing a syntax error that FF and IE don't. Code: var request; request=false; try { request = new XMLHttpRequest(); } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } } } function isAlNum(str){ return /^[a-z0-9]+$/i.test(str); } var preUsername; var same; function updatePage() { if (username.value.length>0){ if ( request.responseText.indexOf("0") == -1 ) {userNameErrorBox.innerHTML=username.value + " has already been taken"; usernameSuccessBox.innerHTML="";} else {userNameErrorBox.innerHTML=""; usernameSuccessBox.innerHTML=username.value + " is available";}} } function nameTest() { if (username.value==preUsername) {same=1;} else {same=0;} if (!isAlNum(username.value)) {if (username.value.length>0) {username.value=preUsername;}} else {preUsername=username.value;} if (username.value.length>0 && username.focus && same===0) { userNameErrorBox.innerHTML="";usernameSuccessBox.innerHTML=""; request.abort(); var url = "/unseen/checkIfUserNameExist.php?name=" + username.value; request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); } if (username.value.length===0) { userNameErrorBox.innerHTML="";usernameSuccessBox.innerHTML="";preUsername=""; } } I back tracked what i did and it appears that this code Code: var url = "/unseen/checkIfUserNameExist.php?name=" + username.value; request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); has the problem. When I set up alerts to see what works and what doesn't, this code seems to be causing the FF and IE to not work, but I can't tell what it is that's causing them to fail. This is javascript that is suppose to check if a name has been taken by another user. I'm working on a fairly large project that I wish to be the new formspring, (size wise) I procrastinated for 2 weeks of my 12 week break and now that I'm just getting started on it I'm running into an ishness load of problems... Very de-motivating Hi I am new to teaching JavaScript I need to show how to create a form with validation and feedback. I can get it to validate a text with a message, but I cannot get it to validate a set of radio buttons and conform the radio selected. Code below- <html> <head> <title>Exam entry</title> <script language="javascript" type="text/javascript"> function validateForm() { var result = true; var msg=""; if (document.ExamEntry.name.value=="") { msg+="You must enter your name \n"; document.ExamEntry.name.focus(); document.getElementById('name').style.color="red"; result = false; if (document.ExamEntry.subject.value=="") { msg+="You must enter the subject \n"; document.ExamEntry.subject.focus(); document.getElementById('subject').style.color="red"; result = false; } } if(msg==""){ return result; } { alert(msg) return result; } } </script> </head> <body> <h1>Exam Entry Form</h1> <form name="ExamEntry" method="post" action="success.html"> <table width="50%" border="0"> <tr> <td id="name">Name</td> <td><input type="text" name="name" /></td> </tr> <tr> <td id="subject">Subject</td> <td><input type="text" name="subject" /></td> </tr> <tr> <td><input type="reset" name="Reset" value="Reset" /></td> </tr> </table> </form> <script type="text/javascript"> function lengthpass() { var s1=document.getElementById("password"); if(s1.value.length != 4) { alert("Please enter an exam number which is 4 characters long"); return false; } return true; } </script> </head> <body> <form onsubmit="return lengthpass();"> Exam Code <input type="text" id="password" name="password"> (Four Numbers) <br> <br> <h1>option button form validation</h1> <script type="text/javascript"> function option1() { var checkedop=null; var examop=document.getElementsByName("exam"); for (var i = 0;i<examop.length;i++) { if(examop[i].checked) { checkedop=examop[i]; } } if(checkedop==null) { alert("please select an exam"); return false; } { confirm("you have chosen"+checkedop.value+ "is this correct?"); } } </script> </head> <body> <form name="examtype" onsubmit="return option1();"> Select an exam type<br> <input type="radio" name = "exam"value= "GCSE"> GCSE<br> <input type="radio" name = "exam"value= "AS"> AS<br> <input type="radio" name = "exam"value= "A2"> A2<br> <input type="submit"name="submit"value="Submit Form"/> </form> </body> </html> index.html Code: <html> <head> <title>:: wtmp</title> </head> <body> <p>Welcome to my page</p> <script type="text/javascript" src="file.js"></script> </body> </html> file.js Code: function one(p1, p2) { var j_text=p1+" "+p2; return j_text; } function two() { var rslt=one("Hi", "there!"); } document.write(rslt); var mainscrpt=one("Hello", "world!"); window.alert(mainscrpt); Simple random pic script that I found on the some other forum (I forget what it was) [CODE]var aryimages = new Array('images/pic/01.jpg', 'images/pic/37.jpg', 'images/pic/02.jpg', 'images/pic/family/08.jpg','images/pic/08.jpg', 'images/pic/food/03.jpg'); randompic.src = aryimages[Math.floor(Math.random() * aryimages.length)]; [CODE] code anchors to HTML markup [CODE]<img name="randompic" id="bg" />[CODE] it is working perfectly for Safari and Chrome. Nothing is showing for FF. Any suggestions appreciated. I have entered the following in a file named welcome.htm when the form is submitted the Test! Alert comes up but the alert fields indicating the fields are empty do not appear. Please let me know if you can see why. Thanks Code: <html> <head> <script type="text/javascript"> alert('Test!'); function submitform() { alert('Test!'); alert('In fname is '+document.form.fname.value); if (document.form.fname.value == ""){ alert('The fnamefield is empty!'); return false; } if (document.form.age.value == ""){ alert('The fnamefield is empty!'); return false; } return true; } </script> </head> <body> <form id="myform" action="welcome.php" method="post" onSubmit="return submitform()" > Name: <input type="text" name="fname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> I have used this formula before, for some reason it isnt working properly. If the value is equal to 0 it will give an alert and return false. Then if you change the value of the drop down it won't let you submit. Does anyone see anything wrong? Code: <script type="text/javascript"> <!-- function validate_form ( ) { valid = true; if ( document.week_picks.blowout.value == "0" ) { alert ( "Please Select a Blowout" ); } return false; } //--> </script> Code: <form name="week_picks" method="post" action="confirm.php" onsubmit="return validate_form()"> <select id="blowout" name="blowout"> <option value="0">..</option> .... </select> Thanks for any help. i am new in programming and learning it from lynda but i am trying to make a program which according to me is good enough but its not working and i am using free javascript editor for compiling and coding <!DOCTYPE html> <html> <body> <script> var a = 5; var b = 10; var c = 30; var d = a + b + c; alert("the value of d is" + d); </body> </html> Please tell me where is it i am making mistake Reply With Quote 01-08-2015, 11:56 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts You forgot the </script> ending tag. Do you see anything wrong with this code... Code: <SCRIPT LANGUAGE="JavaScript"> if(GetCookie('upgrade8') != null) { location.href="cookie-in.html" } </SCRIPT> Also tried this (didn't work either)... Code: <SCRIPT LANGUAGE="JavaScript"> var readCookie = getCookie("upgrade"); if (readCookie("upgrade") != null){ // if cookie already exists, go to url document.location = "lesson1"; } else { // else go someplace else document.location = "lesson2"; }; </script> I've tried posting in both the head and body. Still can't get it to redirect. I'm a little new to this. Your help would be appreciated. thanks |