I'd love to know if there is a possibility to add a trigger ("KEY EVENT"ׁׂׂ) to avoid sending the request twice.
The problem is if we start typing in the URL field the domain http://www.example.com.. The AJAX will trigger on "http://www.example.co" and then again when you add the last letter.
There are an option to avoid that or give the user few second to finish to write the full domain?
<html>
<head>
<script>
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;
return regex.test(url);
}
function showHint(str) {
if (!isUrl(str)) {
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>
Related
this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}
I'm new in Javascript and i'm trying to make an http request to fetch some data and display the results in html. I'm fetching the results and update the html code, but then the html code inside body reloads and shows the default values. My code is,
<head>
<script>
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
xhr.onreadystatechange = processRequest;
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
// populate here results array
// i change the value with the following line
document.getElementById("title_1").innerText = "fetched_value";
}
}
}
</script>
</head>
<body>
<div class="search_btn">
<form id="search_form" method="get" onSubmit="return httpGetAsync()">
<input type="text" class="search" placeholder="Search" id="search">
<input type="submit" value="search" class="search_button">
</form>
</div>
<div id="one">
<p id="title_1">default</p>
</div>
</body>
The 'title_1' changes its text to 'fetched_value' but it then reloads and becomes 'default' again. What am i doing wrong?
It's because your onSubmit does not receive false. Simply add return false to httpGetAsync end
function httpGetAsync() {
var results = new Array(3);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener(
"readystatechange",
function processRequest() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("title_1").innerText = "fetched_value";
}
},
false);
xhr.onreadystatechange = processRequest;
return false;
}
You need to prevent the default action on submit, which is to use the "action" attribute on the form element to reload the page (if it's not present the current page is reloaded).
function httpGetAsync(event) {
event.preventDefault();
...
}
I want to make a page that the user put any word on textbox and returns all books with that word in (books is in mysql and i am gone to convert the query in xmlconvert.php)
<form id="keyword" >
<input type="text" name="value" id="book"/>
<br/>
<button onclick="showhint(functionvalue())">Search By Title</button>
</form>
there is the a function to get the word that user put and send it to ajax showhint();
<script>
function functionvalue() {
var bookname = document.getElementById('book').value;
return bookname;
}
</script>
there is the ajax code that get the responsetext from xmlconvert.php file where I got the q where is the word that user put and make a query with that word and return the books in xml
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("keyword").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET","xmlconvert.php?q="+str,true);
xmlhttp.send();
}
</script>
I don't know if my thought is correct let me know if I can do that and how is possible to make it.
Sorry my English is not so good
You are assigning your new XMLHttpRequest to the variable ajax but then calling its commands with other names. If you named it ajax, you need to do ajax.readyState, ajax.status, ajax.open, ajax.send, etc.
So this should work:
<script type="text/javascript">
function showhint(str){
var ajax=new XMLHttpRequest();
ajax.onreadystatechange=function{
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>
Need to make the following changes:
ajax.onreadystatechange should be a function definition so include () after the function keyword
XMLHttpRequest should be referenced through ajax var.
So the correct code would be:
<script type="text/javascript">
function showhint(str) {
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById("keyword").innerHTML = ajax.responseText;
}
};
ajax.open("GET","xmlconvert.php?q="+str,true);
ajax.send();
}
</script>
I am trying to display contents of a php file on my html page using ajax.
I have an html file with the following ajax code :
get_ajax.html
<form action="">
First name: <input type="text" id="txt1" onblur="show users(this.value)">
</form>
<p>Username: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = newXMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
user.php
<?php
echo $_GET["u"];?>
It doesn't display the username on my get_ajax.html page.
Is there something wrong with my code?
First check the existence of user.php and verify the proper path,by the way why don't use Jquery,it is easy and straight forward.
Here is an example using jquery :
var str = 'something';
$.get('user.php',{u:str},function(serverResponse){
$("#txtHint").html(serverResponse); //this should add the value something to the DOM
});
Appears you have type in your code as below
- onblur , you are making a call to "show users(this.value)"
- there is a space between "show" and "user" , even u correct the space , you dont have a function "showuser" anywhere.
- your function to make the ajax call is "showHint"
- next you need a space between "new" and "XMLHTTpRequest()"
<form action="">
First name: <input type="text" id="txt1" onblur="showHint(this.value)"/>
</form>
<p>Username: <span id="txtHint"></span></p>
</form>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
I want to use Javascript to validate my input username if it is correct or not showing result on realtime.
Here is index.html code:
<html>
<head>
<script>
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
Type a username: <br>
<input id="hint" type="text" name="username" oninput="showHint(this.value)"><p id="hint"></p>
</body>
</html>
Here is the demo3.php code:
<html>
<head>
</head>
<body>
<?php
$mysqli = new mysqli("localhost","root","123456","mini");
$username = $mysqli->real_escape_string($_REQUEST['input']);
$sql = "SELECT username FROM `users` WHERE username='$username'";
$result = $mysqli->query($sql);
if($result->num_rows){
echo "Valid username";
}else{
echo "Invalid username";
}
?>
</body>
</html>
I use the oninput event example from w3cschools, and I am wondering why my result do not show what I expect?
And if I assign $username with static variable, demo3.php result seems to be correct feedback, not from index.html.
Plus, I am wondering how to validate multiple forms, such as password and email within the same validation php file.
Ex:
input1 -> check username ->output check result
input2-> check password ->output check result
input3-> check email->output check result
New to javascript.All the tutorial seems to provide only one demo, not multiple examples.
Since your input is being placed in the URL, you will need to use the GET parameter other than POST (which does not use the URL):
xmlhttp.open("GET", "demo3.php?input=" + str, true);
Now it should be able to pickup your input for $_REQUEST['input'] or $_GET['input']
The problem is that you are using the ID "hint" twice. ID is a unique identifier, so you NEVER should use it more than once in the same page. And you should avoid using inline handlers. You need to change your javascript to:
<script>
window.onload = function() {
function showHint(str){
if(str.length == 0){
document.getElementById("hint").innerHTML = "";
}else{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "demo3.php?input=" + str, true);
xmlhttp.send();
}
}
document.getElementById("hintInput").onkeyup = function() {
showHint(this.value)
}
}
</script>
and your HTML:
<input id="hintInput" type="text" name="username"><p id="hint"></p>
You can get rid of window.onload if you place your script tag before closing the body tag.