How do you use AJAX using user input? - javascript
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();
}
Related
How to search for items in a list in javascript?
I have a requirement to search github API for fetching repositories or users and display it. I have tried the below code, but cannot able to filter by name from API. Can someone help on this? var searchValue = document.getElementById("search").innerHTML; function UserAction() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { alert(this.responseText); //Show the name based on filter if (searchValue.toUpperCase().indexOf(filter) > -1) { //display the list of users below } } }; xhttp.open("GET", "https://api.github.com/search/repositories?q="+searchValue, true); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.send("Your JSON Data Here"); } Search Repo..<input type="text" name="search" id="search" placeholder="Search for names.." onkeyup="UserAction()" /> I'm expecting an output like below in pure javascript, strictly no jquery or any other frameworks. Can someone help on this?
First you need to retrieve the value from the input after it's been typed in. Right now you're just getting the undefined value. Once you have that, you need to parse the response from GitHub into an object, look for the parts of the response you are interested in, and compare to your filter. Here we compare the search term to the repo name and the owner login. I've also added some rudimentary debounce code, you might be able to come up with something more robust with some work. There's no error checking here, which you'll probably want, and I'm just dumping the output into a div — you'll probably want to style that. Hopefully that will give you enough to get started. var debounceInterval var debounceWaitTime = 200 // ms // simple debounce function UserAction() { clearInterval(debounceInterval) debounceInterval = setTimeout(sendRequest, debounceWaitTime) } function sendRequest() { let out = document.getElementById('output') out.innerHTML = '' // you need to get this value here, not just once at the beginning var searchValue = document.getElementById("search").value; var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { let resObj = JSON.parse(this.responseText); //Show the name based on filter resObj.items.forEach(item => { // look in full_name and owner.login for searchValue if (item.full_name.toUpperCase().includes(searchValue.toUpperCase()) || item.owner.login.toUpperCase().includes(searchValue.toUpperCase())) { out.innerHTML += "Repo: " + item.full_name + ' Owner: ' + item.owner.login + '<br>' } }) } }; xhttp.open("GET", "https://api.github.com/search/repositories?q=" + searchValue, true); xhttp.setRequestHeader("Content-type", "application/json"); xhttp.send("Your JSON Data Here"); } Search Repo..<input type="text" name="search" id="search" placeholder="Search for names.." onkeyup="UserAction()" /> <hr /> <div id="output">
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()".
JSP Chat - How I can parse the value from HTML to JSP page?
I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null. If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that. I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem). How I can make to populate 'textParam' with the input text value when I press the button? PS: I need to make it with pure javascript, not with some libraries :) The JSP which have to process is: String textParam = request.getParameter("chatMessage"); System.out.println("textParam = " + textParam); My form it look like that: <form id="frmmain" name="frmmain" onsubmit="return blockSubmit();"> <input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" /> <input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" /> </form> The .js file it's this: var request = getXmlHttpRequestObject(); var response = getXmlHttpRequestObject(); var lastMessage = 0; var mTimer; function getXmlHttpRequestObject() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } else if(window.ActiveXObject) { return new ActiveXObject("Microsoft.XMLHTTP"); } } function sendChatText() { if(document.getElementById('chatMessage').value == '') { alert("You have not entered a message"); return; } if (request.readyState == 4 || request.readyState == 0) { request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true); request.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); request.onreadystatechange = handleSendChat; var param = 'message=' + document.getElementById('chatMessage').value; param += '&chat=1'; request.send(param); document.getElementById('chatMessage').value = ''; } } function handleSendChat() { clearInterval(mTimer); getChatText(); } function blockSubmit() { sendChatText(); return false; }
The problem is here: String textParam = request.getParameter("chatMessage"); I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js: String textParam = request.getParameter("message");
Simple Python and Ajax Example How to Send Response with Python?
I am testing out some code with Python and Javascript trying to get an Ajax system set up. Basically I just want to input a word and have the python code send it back. Here is my html/javascript: <html> <head> <title>Simple Ajax Example</title> <script language="Javascript"> function xmlhttpPost(strURL) { var xmlHttpReq = false; var self = this; // Mozilla/Safari/Chrome if (window.XMLHttpRequest) { self.xmlHttpReq = new XMLHttpRequest(); } // IE else if (window.ActiveXObject) { self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } self.xmlHttpReq.open('POST', strURL, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); self.xmlHttpReq.onreadystatechange = function() { if (self.xmlHttpReq.readyState == 4) { updatepage(self.xmlHttpReq.responseText); } } self.xmlHttpReq.send(getquerystring()); } function getquerystring() { var form = document.forms['f1']; var word = form.word.value; qstr = 'w=' + escape(word); // NOTE: no '?' before querystring return qstr; } function updatepage(str){ document.getElementById("result").innerHTML = str; } </script> </head> <body> <form name="f1"> <p>word: <input name="word" type="text"> <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/ajaxtest")'></p> <div id="result"></div> </form> </body> </html> and here is my python: class AjaxTest(BlogHandler): def get(self): user = self.get_user() self.render('ajaxtest.html', user = user) def post(self): user = self.get_user() word = self.request.get('w') logging.info(word) return '<p>The secret word is' + word + '<p>' #having print instead of return didn't do anything When I do logging the word shows up correctly and when I hardcode str in: function updatepage(str){ document.getElementById("result").innerHTML = str; } It displays that correctly but right now without hardcoding it shows nothing. How am I supposed to send the response? I am using webapp2 as my Python framework and Jinja2 as the templating engine, though I don't think that has much to do with it. Do I need to send the HTTP headers?
If your problem is having difficulty returning a string from your post method, without rendering a template you can use the write method to accomplish that: self.response.write('') I believe you can change headers by just modifying self.response.headers
javascript ajax innerHTML confusion
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.