JavaScript - Simple Ajax Request
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 Similar TutorialsHi, I have searched and searched... Is there a way of using the Ajax httpRequest cross domain? thanks Hi there, I am trying to make a view that stacks images on top of one another. As the user uses mouseup or mousedown (+ LMB click) the user can scroll through the images. I am trying to use Ajax to load the new image when the user mousesup. RIght now nothing happens on mouseup. Can someone tell me what I am doing wrong please? thank you. FYI: no errors on Firebug, hence I am posting here. Code: $("#filmviewer").mouseup(function(){ alert("t"); }); html Code: <div id="filmviewer" style="width:400px;"> <img src="pic_1.jpg" /> </div> The problem is when I click and mouseup over the image the alert("t") does not fire. what am I doing wrong? Hey, as the subject says... I'm struggling to call other external files from within a file, requested by an Ajax.Request. It's bascically a request to call a file that updates a mysql database, and I want to include my database connection php file so I don't have to keep repeating my connection settings. here is the request: Code: new Ajax.Request('tools/server_reorder_list.php', options); and within that file I'm trying to do something like this: Code: include ("../config/dbconnect.php"); $i=1; foreach($_POST['item_list'] as $key=>$value) { mysql_query("UPDATE `cs_pages` SET `position`='".$i."' WHERE id_page ='".$value."'"); $i++; } I've tried all kinds of ways to include the files, from the above, to typing the entire path. The only way I can get this request to work is by actually typing my connection settings in the requested file. Any help greatly appreciated. Thanks! Could someone help me figure out why this AJAX request is not completed in Internet Explorer. Thanks. Code: function openmanagegraphs() { document.getElementById('managegraphs').style.display = 'block'; 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) { document.getElementById("results").innerHTML = xmlhttp.responseText; } } xmlhttp.open("POST", "PHP/mgon.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); CurrentRun; xmlhttp.send("mgon=true"); } I am using this code... simplified for example Code: [ <script type="text/javascript"> function loadContent(elementSelector, sourceURL) { $(""+elementSelector+"").load(""+sourceURL+""); } </script> <a onclick="loadContent('#content', 'http://www.website.com/includes/content.php');" <div id="content"></div> Works fine if run on http://www.website.com but not on http://www.website.com/home/sitepage. I have spent a few hours and cannot figure it out. Can anyone? Thanks I'm using jquery right now but I sort of understand what the problem is. I'm making a file manager and when you click on an li tag it will do some action depending on if it's a file type or a folder type. There are 3 important files you should know about. 1. filemanager.php (Where the file managing takes place. Starts by including filemanager_getfile.php and including filemanager.js in the head). 2. filemanager_getfile.php (Information that receives information from the ajax request [the directory to be read] and prints the new file list in <li> tags) 3. filemanager.js (Jquery that processes li clicks) The problem is, when you click on a folder (and it loads the new information from the ajax request) the jquery doesn't check the new li tags when clicked (I'm guessing when you first link the javascript file it has to compile all of the current li information?). Try it for yourself- [removed] Instruction (if it's not already obvious): -Clicking a file selects if. If files are selected and you click the arrow in the file options it will transfer it (not really, but it will later). -Clicking a folder will send an ajax request with the new directory information to be checked and return the html -Clicking the '?' in the file options will display the pages html (I implemented it to debug). I have tried linking the js page every time I include the new directory information, but the js stacks on each other. So if I click on 3 folders and hit the '?' button it will display the page html 3 times. And if I select the index.php li and click transfer, it will "transfer" 3 times. filemanager.php Code: <div id="goldenSub"> <div class="title">Golden Subdomain</div> <div class="files" id="goldenSubFiles"> <? include("filemanager_getfiles.php"); ?> </div> <div id="history" visited="goldensub/"></div>; <div class="fileOptions"><img src="images/question.png" title='HTML Information' id="ask"><img src="images/transferto.png" title='Copy File To' id="transferTo"></div> </div> filemanager_getfiles.php PHP Code: <? $path = $_REQUEST["dir"]; if($path == "" || $path == null) { $path = 'goldensub/'; } echo "\n<div class='path'>$path</div>\n<ul>\n"; $handler = opendir($path); //We need to organize the results. Be default, all files and folders will be //located by alphabetical order. But we want to list all folders first, followed //by files. By adding the results to arrays first we can decide to print our //results in the order we want. $folderArray = array(); $fileArray = array(); $folderCount = 0; $fileCount = 0; while(false !==($file=readdir($handler))) { if($file != "" && $file != null && $file != "." && $file != "..") { $extensionLocation = strrpos($file, "."); //Is this a folder or a file? if($extensionLocation == null && $extensionLocation == "") { //This is a folder unless it's the error_log file. if($file != "error_log") { //Nope, it's definitly a folder. Add it to the folder array. $folderCount++; $folderArray[$folderCount] = $file; } } else { //This is a file. Add it to the file array. $fileCount++; $fileArray[$fileCount] = $file; } } } if($path != 'goldensub/') { echo "\t<li title='goldensub/' type='folder'>\n\t\t<img src='images/up.png'> goldensub\n\t</li>\n"; } for($i = 1; $i<=$folderCount; $i++) { $newPath = $path.$folderArray[$i].'/'; echo "\t<li title='$newPath' type='folder'>\n\t\t<img src='images/folderOpen.png'> $folderArray[$i]\n\t</li>\n"; } for($i = 1; $i<=$fileCount; $i++) { $extensionLocation = strrpos($fileArray[$i], "."); $nameLength = strlen($fileArray[$i]); $extensionLength = $nameLength-$extensionLocation; $nameClean = substr($fileArray[$i], 0, $extensionLocation); $extension = substr($fileArray[$i], $extensionLocation+1, $nameLength); echo "\t<li title='$fileArray[$i]' type='file' extension='$extension'>\n\t\t\n\t<img src='images/$extension.png'> $nameClean\n\t</li>\n"; } echo "</ul>"; ?> filemanager.js Code: $("li").click(function(){ var type = $(this).attr("type"); //This is a folder if(type == "folder") { //Path to new directory var newPath = $(this).attr("title"); //Ajax request to filemanager_getfiles.php $("#goldenSubFiles").load("filemanager_getfiles.php", { dir: newPath }, function(data){ //Update log newLog("Directory changed to <i><b>"+newPath+"</b></i>"); }); } //This is a file else { if($(this).hasClass("selected")) { //It's already selected - deselect it. $(this).removeClass("selected"); } else { //Select it $(this).addClass("selected"); } } }); Hi, First i don know if im posting at the right place or if you even take request here, feel free to direct me to the right place. What i am looking for is someone to make a simple counter for me. Basically i want that every time i press a certain key on my keyboard it will increase the counter amount and would then divide it by 60 every hour. Actually im looking for it to only show that average and refresh every hour. So it would start at 0 then update after the first hour and so on. (I also need a graphical interface) I have very few knowledge in coding and would very appreciate if someone could do that for me. Thank you ! Reply With Quote 01-10-2015, 11:39 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 I don't think this is something you would do with JavaScript. I think you need a ".exe" (on Windows) program. And that's a lot more complex. The problem is your request to capture a certain key, presumably no matter what window is at the front. Normally, within a given window, you can only capture a key that is intended for that window. I don't think this is a very easy thing to do. 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. 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. Hi, I am hoping I just need to be pointed in the right direction with this. I have Page1. When Page1 body onloads it uses Ajax to call PartA Within PartA I have a message board so members can write messages which will be sent to my database in PartA[1] and immediately posted for view on to PartA[2]. As I want to have my request to the server updating regularly I want to have PartA[2] on a timed loop to refresh - I do not need the content of PartA[1] to refresh. So the order of events would look like this: Page1 | onload call | v PartA / \ V V PartA[1] PartA[2] (loads once) (constantly refreshes) What I am not sure about is that I have <body> and <head> attributes in Page1 only. I have already used my body onload to call PartA (and can't use it to call PartA[2] before PartA has loaded anyway). I do not want the user to have to click a button or do anything to call up PartA[2]. So my question is how would I get PartA[2] to automatically load within PartA? I hope I have made this clear, but if I haven't let me know and I will try again. I'm not a programmer, just a lowly photographer that manages some websites. A company that provides Print-on-Demand services for me has some code that works in most browsers, but not in IE (at least older versions). It has to do with an onClick routine, and after some google searchs, I saw that similar issues have been common for years. Yet I didn't really understand the solutions. I put up a test page with the relevant code snippet. In Chrome, if one clicks on the image, the sales page comes up. In IE, nothing happens. I gathered that any error will bog down IE. If someone recognizes the problem or knows of a solution, I would be most grateful. The example page is here. The code snippet is below. Thanks in advance for anyone taking the time to look. <img src='http://images.fineartamerica.com/images-medium-large-5/autumn-peak-at-oxbow-bend-greg-norrell.jpg' style='position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; border: none; z-index: 0;''> <div onTouchEnd='javascript: if(tap){window.location="http://photoartresource.com/featured/autumn-peak-at-oxbow-bend-greg-norrell.html";}' onClick='javascript: window.location="http://photoartresource.com/featured/autumn-peak-at-oxbow-bend-greg-norrell.html";' style='position: absolute; width: 100%; height: 100%; background-color: transparent; z-index: 1;'> </div> Can someone modify the code below to save name & email to a file named logfile.dat please? Code: <html> <HEAD> <SCRIPT language="JavaScript"> function WriteFile(name, email) { var fso = new ActiveXObject("Scripting.FileSystemObject"); var fh = fso.CreateTextFile("D:\\logfile.dat", true); fh.WriteLine(name); fh.WriteLine(email); fh.Close(); } function sendtopage(whatpage) { alert(whatpage) window.location.href =whatpage; return true; } redirectTime = "3000"; redirectURL = "http://www.cnn.com"; function timedRedirect() { alert('Thank you'); setTimeout("location.href = redirectURL;",redirectTime); } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkEmailCookie() { var email=getCookie("email"); if (email!=null && email!="") { alert("Email: " + email); } } function checkNameCookie() { var name=getCookie("name"); if (name!=null && name!="") { alert("Name: " + name); } } </SCRIPT> <style type="text/css"> .Class01 { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; font-size: 24px; font-weight: bold; } .Class02 { font-size: 36px; font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; } .Class013 { font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; } .Class01 .Class013 .Class01 { font-weight: bold; } .Classzz { font-family: "Lucida Console", Monaco, monospace; } .Classxx { font-weight: bold; font-size: 24px; } .Classzz { font-family: "Lucida Console", Monaco, monospace; } .style1 { text-align: center; } </style> </HEAD> <body gcolor="#FFFFFF" background="../MCM-background.jpg"> <center> <p class="style1"><img src="../mcm_header2.gif" alt="Header" width="790" height="199"></p> </center> <p></p> <form name="fm" action="http://www.meadecountymessenger.com"> <div align="center"> <p> </p> <p><span class="Class01"><span class="Class02">Please enter the following.</span></span></p> <p> </p> <p><span class="Class01">Your Name: </span> <input name="name" type="text" size="60" /> </p> <p><span class="Classzz"><br /> <span class="Classxx">Your eMail:</span></span><span class="Class01"> </span> <input name="email" type="text" size="60" /> <script type="text/javascript"> setCookie("email",document.fm.email.value,365); setCookie("name",document.fm.name.value,365); </SCRIPT> </p> <p> <input name="" type="submit" class="Class01" OnClick="alert('Thank You !');" value="Submit"/> </p> </div> </form> </body> </html> Hi. I need to load an iFrame, take the contents from it, and pass it to a file (getjson.php), which will pass data back to the file, and then display it in a div. I've tried so many different ways. The main file is on mydomain.com, and the file I'm accessing is on mydomain.com:2086, just so you know. Hey all, Was just wondering if anyone knew what type of content slider is this http://www.builtbybuffalo.com/ and were could i get one? Thanks in advance Kyle i m trying to implement captcha in my site.i m using recaptcha. To check the captcha i need to request url like: http://www.google.com/recaptcha/api/verify?privatekey="key"&remoteip="ip"&challenge="chal"&response="res" and then i need to check response from url if it is true or false i dont know how to request response from url help plz HI there.. Can you please give me code in JavaScript to create a student request form for book request from issue section of college Library.. Please help with code... Thanx in advance... Regards, I use [Fiddler](Understanding FiddlerScript ), Man in the middle proxy tool Code: var regex = /TargetString/gi ; if (regex.match(URL) { var request_arr = new Array( "www.bing.com", "www.google.com", "www.yahoo.com", "www.sandbox.com"); var random_url = request_arr[Math.floor(Math.random() * request_arr.length)]; Basically, The above code says, if the TargetString is found in URL, then redirect it to a random URL. What I need, For example: If TargetString is found in www.example.com/TargetString redirect to by picking a random URL from array list and NOT to use THAT URL in the future Thank you Hi; I have three files login.php, process.php and catcher.php. The first one contain the form, the second file is the form action and the last is a second file which must receive the form request as well but not getting redirected to it. login.php content : PHP Code: <form action="process.php" method="post"> <input type="text" name="userid"> <input type="password" name="userpwd"> <input type="submit" value="Submit"> </form> So I want the user who click on the Submit button get redirected to process.php as usual and at the seem time send a copy of the request into catcher.php. I am thinking for a hidden iframe but don't know how to de it. Regards I have a text box that is updated automatically via a javascript that posts back. It works fine in IE, but not in firefox. I know I call the aspx correctly, because other code work. I tried to insert the URL that I send in the browser, and it returns data. So either the event handler is never called, or else the response is empty in firefox. Any ideas? Code: function CreateReq() { var xmlhttp=false; /*@cc_on @*/ /*@if (@_jscript_version >= 5) // JScript gives us Conditional compilation, we can cope with old IE versions. // and security blocked creation of the objects. try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @end @*/ if (!xmlhttp && typeof XMLHttpRequest!='undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp=false; } } if (!xmlhttp && window.createRequest) { try { xmlhttp = window.createRequest(); } catch (e) { xmlhttp=false; } } return xmlhttp; } function fetch(){ var xmlhttp=CreateReq(); //alert ("fetch"); xmlhttp.open("GET", "CtrlLoader.aspx?MachinePrefix="+ document.getElementById('LblMachinePrefix').value+ "&RequestTime="+ (new Date()).getTime()+"&method=Refresh",false);//was true xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4) { document.getElementById('TxtCtrlConsole').value+=xmlhttp.responseText; for (var i=0;i<200;i++) document.getElementById('TxtCtrlConsole').scrollTop=document.getElementById('TxtCtrlConsole').scrollHeight; } } xmlhttp.send(null); } Edit: it appears, that it s the onreadystate function that is never called. I tried adding an alert to it. I also tried init of onreadystatechange before open. No effect for firefox Hi, how to call the rest api via xml http request? I am working in oodle api,i am new for api.how to call the oodle server and retrieve data on xml format?pls help......... send javascript or ajax sample codings............. thanks |