javascript ajax innerHTML confusion - javascript
So, I'm pulling a query from a php file using javascript, then publishing it to another javascript that will then put another php query in another text area.
In other words:
[input text area 1] -> [javascript live search] -> [Query results]
[Query results] -> [onClick event] -> [Load results in text area 2]
The idea is that live searches in one textarea will come out with its approximate match in another live.
However, when I try to load the data in the second textarea it comes out as raw data. I'm confused on how to view it properly.
HTML:
The first text area is the input with a function to call a script, which is here:
function showResult(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border = "0px";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("livesearch").innerHTML = xmlhttp.responseText;
document.getElementById("livesearch").style.border = "1px solid #000";
}
}
xmlhttp.open("GET", "ajax-search.php?keyword=" + str, true);
xmlhttp.send();
}
The php returns the result:
echo '<li onclick="grabID('.$row['dir_id'].')" >'.$row['eng_dir'].'</li><br />';
Which then initiates a clicked event:
function grabID(num){
xmlhttp.open("GET","ajax-result.php?result="+num,true);
xmlhttp.send();
document.getElementById("output").innerHTML="Something here?!?!?!";
}
Once again the results from the other php are returned correctly. The problem is that because it's a loop, it returns a lot of results instead of just 1. I just want the 1 result that matches the ID of the previous search.
Related
Auto Link shorting via PHP&AJAX (bit.ly)
I would like to build a form (VIA POST METHOD) with just one field (url - link shortening). Now the question is how and if is it possible to build a form that detects the value of the URL field is a link and automatically shortens it rather than waiting you click Send (for exmaple like the web of Bit.ly). The main idea is once the field is an identifier that value is a proper Hyperlink is directly sends and shortens (And the field is replaced by a shortened link) it without waiting for the click on the SEND. index.html <html> <head> <script> function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } } </script> </head> <body> <p><b>Start typing a url in the input field below:</b></p> <form> Url: <input type="text" onkeyup="showHint(this.value)"> </form> <p><span id="txtHint"></span></p> </body> </html> gethint.php <?php // get the q parameter from URL $q = $_REQUEST["q"]; $hint = ""; if (!filter_var($q, FILTER_VALIDATE_URL) === FALSE) { // short the link $rand = rand(1,1000); $hint = 'http://domain.com/'.$rand; } echo $hint === "" ? "Not a valid URL" : $hint; ?>
I'd use jQuery for the event triggering/AJAX and https://gist.github.com/dperini/729294 for weburl regex. I'm not that at home on pure JavaScript AJAX calls, but is xmlhttp.open("GET") the right way to go at it if you want to make a POST? Anyway the main thing you're missing is function isUrl(url){ var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i; if(regex.test(url)){ return regex.test(url); }else{ return regex.test("http://"+url); } } So this should be your new index.html <html> <head> <script> var extensions = [".aero",".biz",".cat",".com",".coop",".edu",".gov",".info",".int",".jobs",".mil",".mobi",".museum",".name",".net",".org",".travel",".ac",".ad",".ae",".af",".ag",".ai",".al",".am",".an",".ao",".aq",".ar",".as",".at",".au",".aw",".az",".ba",".bb",".bd",".be",".bf",".bg",".bh",".bi",".bj",".bm",".bn",".bo",".br",".bs",".bt",".bv",".bw",".by",".bz",".ca",".cc",".cd",".cf",".cg",".ch",".ci",".ck",".cl",".cm",".cn",".co",".cr",".cs",".cu",".cv",".cx",".cy",".cz",".de",".dj",".dk",".dm",".do",".dz",".ec",".ee",".eg",".eh",".er",".es",".et",".eu",".fi",".fj",".fk",".fm",".fo",".fr",".ga",".gb",".gd",".ge",".gf",".gg",".gh",".gi",".gl",".gm",".gn",".gp",".gq",".gr",".gs",".gt",".gu",".gw",".gy",".hk",".hm",".hn",".hr",".ht",".hu",".id",".ie",".il",".im",".in",".io",".iq",".ir",".is",".it",".je",".jm",".jo",".jp",".ke",".kg",".kh",".ki",".km",".kn",".kp",".kr",".kw",".ky",".kz",".la",".lb",".lc",".li",".lk",".lr",".ls",".lt",".lu",".lv",".ly",".ma",".mc",".md",".mg",".mh",".mk",".ml",".mm",".mn",".mo",".mp",".mq",".mr",".ms",".mt",".mu",".mv",".mw",".mx",".my",".mz",".na",".nc",".ne",".nf",".ng",".ni",".nl",".no",".np",".nr",".nu",".nz",".om",".pa",".pe",".pf",".pg",".ph",".pk",".pl",".pm",".pn",".pr",".ps",".pt",".pw",".py",".qa",".re",".ro",".ru",".rw",".sa",".sb",".sc",".sd",".se",".sg",".sh",".si",".sj",".sk",".sl",".sm",".sn",".so",".sr",".st",".su",".sv",".sy",".sz",".tc",".td",".tf",".tg",".th",".tj",".tk",".tm",".tn",".to",".tp",".tr",".tt",".tv",".tw",".tz",".ua",".ug",".uk",".um",".us",".uy",".uz", ".va",".vc",".ve",".vg",".vi",".vn",".vu",".wf",".ws",".ye",".yt",".yu",".za",".zm",".zr",".zw"]; var delay = (function(){ var timer = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); function isUrl(url){ var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?#)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i; if(regex.test(url)){ return regex.test(url); }else{ return regex.test("http://"+url); } } function showHint(str) { delay(function(){ str = str.toLowerCase(); var dot = str.lastIndexOf("."); var extension = str.substr(dot); extension = extension.split('/')[0]; var found = $.inArray(extension, extensions) > -1; if (!isUrl(str)||!found) { document.getElementById("txtHint").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("txtHint").innerHTML = this.responseText; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } }, 500) } </script> </head> <body> <p><b>Start typing a url in the input field below:</b></p> <form> Url: <input type="text" onkeyup="showHint(this.value)"> </form> <p><span id="txtHint"></span></p> </body> </html> edit: Say you will start typing in http://www.example.net.. The AJAX will trigger on "http://www.example.ne" and then again when you add the last letter. To avoid that, you might try "change" instead of "keyup" event. edit2: Now checks against list of valid domain extensions edit3: Now waits half a second before posting the result. edit4: Small oversight while checking for extensions, fixed with extension = extension.split('/')[0]; Also if you want to enable users to write URL's without "http://" and similar, you'll need an edited regex or write a small hack that adds that to your string before you send it into "isUrl()".
Execute js function after ajax content have been applied to an element
I have a js AJAX that fetches some content and inserts it into a html element called content_holder. And I would like to call a function right after the content have been updated with the ajax. I have tried to put a <script> element into the content that gets added but it seems like it don't get executed. So I was hoping someone here would know a solution to this. (I'm not using jQuery) function ajax(instruction, push, url, callback){ var xmlhttp; // the object for the httprequest 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() { // every time the readystate changes if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done) var content = xmlhttp.responseText + "<script>ajaxDone();</script>"; callback(content); // goes to the callback function (from the argument "callback") and then passes the xmlhttp } }; xmlhttp.open(instruction,url,true); // sends a the var q to the next php file xmlhttp.send(''); // Sends the request if(push == true){ // Change the link to the url of the ajax with var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !! var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY) return; // exit's the function }else{} var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file window.history.pushState({path:urlPath},'',newLink); // the push } else{} } <p>Top Lists</p> <div id="content_holder"></div>
Take a look at this topic: How to make an AJAX call without jQuery? You can do smth like: xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == XMLHttpRequest.DONE ) { if(xmlhttp.status == 200){ document.getElementById("myDiv").innerHTML = xmlhttp.responseText; //here you call whichever function you want } ..... } Hope it helps
How do you use AJAX using user input?
I have a project to build a very simple web page which will utilize AJAX to display a result. In main.py we have a list of words, words = { 'a': True, 'aah': True, 'aahed': True, 'aahing': True, .............. } And we already have this class defined for us: class CheckWordHandler(webapp2.RequestHandler): def get(self): word = self.request.get('word') if word in words: self.response.out.write('true') else: self.response.out.write('false') def post(self): return self.get() So far this is the only thing I have working on index.html which uses AJAX, whenever you type something it just displayed a new random number. I did this just to get a feel for how it works. function checkWord() { var xmlHttp = createXmlHttp(); xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState == 4) { var text = Math.random(); var d = document.getElementById('texthere'); d.innerHTML = text; } } postParameters(xmlHttp, '/check', ''); } But I'm having troubling thinking how to use checkwordhandler to display if the user is typing in a word which is in the list. How would I get the user input to be checked by the handler? I have a form, where the user can type in anything <form > Enter a word:<br> <input type="text" onkeypress="checkWord()" name="word"> <br> </form> So, how would I go about taking the input from this form and checking if it's in the list of words using xml?
Change the input to send the value that the user has typed: onkeypress="checkWord(this.value)" And change the AJAX function to send the value as a parameter, and show the response text. function checkWord(word) { var xmlHttp = createXmlHttp(); xmlHttp.open('GET', '/check?word=' + encodeURIComponent(word), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { var text = xmlHttp.responseText; var d = document.getElementById('texthere'); d.innerHTML = text; } } xmlHttp.send(); }
xmlHttpRequest.send(Params) not working in tomcat 7
I am trying to send some parameters through xmlHttpRequest.send(params) written in a JS file to my servlet where I try to get the parameters by req.getParameter("some_Parameter"); it returns null on the servlet. though if i send the parameters by appending them in url it works fine. but when the url will be large it will break the code. so please someone help me out. Thanks in advance. function doHttpPost(theFormName, completeActivity) { var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); var xmlMessage = buildPOST(theFormName, completeActivity); var responseTxt; try { xmlhttp.Open(document.forms[theFormName].method, document.forms[theFormName].action+'?'+xmlMessage, false); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4) { responseTxt = xmlhttp.responseText; } } xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); enableDisableLinks(true); setPointer(); xmlhttp.Send(); if(xmlhttp.Status != 200) { alert("Post to server failed"); } } catch (e) { responseTxt = "Exception while posting form data: Error No: " + e.number + ", Message: " + e.description; } resetPointer(); enableDisableLinks(false); var expectedTxt = "Form Data had been successfully posted to the database." if(responseTxt.toString() == expectedTxt.toString()) { // MNP: New requirement from Jeanne, should not refresh CM page, commenting it off for now //if(completeActivity) { // if (typeof (ViewCaseDetailBtn) != 'undefined') { // ViewCaseDetailBtn.click(); // } //} return true; } else { alert (responseTxt); } return false; }
BUGS //IE only - shooting yourself in the // Not all IE versions use ActiveX! var xmlhttp = new ActiveXObject("MSXML2.XMLHTTP"); foot. //JavaScript case sensitive, open !== Open xmlhttp.Open(document.fo... //JavaScript case sensitive, send !== Send xmlhttp.Send(); //JavaScript case sensitive, status !== Status xmlhttp.Status AND if you are using synchronous, it does not call the onreadystatechange. If you are using POST, the value needs to be in send("valuestosendup") not on the querystring. This code shows why you should really use a framework to make Ajax calls and to not roll your own.
Popup preview of a textarea using a PHP function
I'd like to make a popup preview of a textarea, using a PHP function inside the popup. Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript). Is it possible to do so ? I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly. I did the following: function PreviewMe() { var newWin = window.open("", "_blank"); newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>"); newWin.document.close(); } and <textarea id="myText" ... /> <input type="submit" ... onclick="PreviewMe();"> Obviously it works without reformatting anything, so how to reformat this result in the popup please ? Would it be possible (and mayber a better option) to use XMLHttpRequest ? Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end. In case it might help others, here is what I've done. Js function became : function PreviewMe() { var xhr = null; if (window.XMLHttpRequest || window.ActiveXObject) { if (window.ActiveXObject) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } } else { xhr = new XMLHttpRequest(); } } else { alert("XMLHTTPRequest not supported..."); return; } xhr.open("POST", "page.php", true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) { document.getElementById('show').innerHTML = xhr.responseText; } }; xhr.send("var="+document.getElementById('myText').value+""); return; } Of course page.php includes my PHP function, show is the id of the div where the result is printed.