Javascript validate username on PHP with realtime output - javascript

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.

Related

Change inner HTML based on PHP return

I have a simple web page with a form consisting of a text entry box and a button. The onclick event of the button fires a script in the head. The script calls a separate PHP page, and checks the submitted text. If the value is "foo" it should say correct, if it's anything else it should say incorrect.
No matter how I tweak it, I can't get anything to show up in the inner HTML of the div with the id of response_one. I'm working off of the W3Schools tutorial found here but just can't seem to make this work. I've included the html / PHP below, any pointers would be greatly appreciated.
The HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
<script>
function show(str) {
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="mainbody">
<form>
Answer: <input type="text" name="answers">
<input type="submit" onclick="show(this.value)">
</form>
<div id="response_one"></div>
</div>
</body>
</html>
and check_one.php:
<?php
$q = $_REQUEST["q"];
$q = strtolower($q)
$result = ""
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result
?>
Problems
Multiple problems here:
Your button is a submit input. On click, your browser will submit the form. None of your AJAX would matter because the page will refresh before you see any result.
Your button does not hold the value. The input field <input type="text" name="answers"> does. It is a mistake to run show(this.value) because you don't really plan to check the submit button's value.
There are multiple syntax error in your check_one.php file. Please run command line php -l check_one.php or use browser to browse check_one.php?q=foo to check it.
Quick Fix
I'll leave the php syntax error to you and focus on your form. Here is how I'm going to fix it:
Change the submit button from <input type="submit"> to <button type="button">. This will prevent form submission on click.
Alter the onClick function to access the value of your text input answers instead of this.value.
The Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
<script>
function show(str) {
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div id="mainbody">
<form>
Answer:
<input type="text" name="answers">
<button type="button" onClick="show(this.form['answers'].value)">Check</button><!-- only this line is changed -->
</form>
<div id="response_one"></div>
</div>
</body>
</html>
Once you fixed your check_one.php, you'll get your desired result.
Room for Improvement
There can still be problem with your form. If the user press "Enter" instead of clicking the button, your form will be submitted. So instead of just intercepting the click event of the button, you'd be better off capturing the form's submit event.
So here are the improvements:
Add an id attribute to your form.
Use document.getElementById to find the form and intercept the submit event.
Use event.preventDefault() to prevent form submission.
Find the answers value and do the XMLHttpRequest.
The Code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>See</title>
</head>
<body>
<div id="mainbody">
<form id="check-form"><!-- added id="check-form" -->
Answer: <input type="text" name="answers">
<input type="submit"><!-- removed onClick attribute -->
</form>
<div id="response_one"></div>
</div>
</body>
<script>
// Moved script after body so the form element would exist before
// this script is run.
document.getElementById('check-form').addEventListener('submit', function (evt) {
evt.preventDefault(); // prevent form submission
var str = evt.target["answers"].value; // get the answers field value
// The logics previously in your `show()` function
if (str.length == 0) {
document.getElementById("response_one").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response_one").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "check_one.php?q=" + str, true);
xmlhttp.send();
}
});
</script>
</html>
It seems you have forgot some of the ";" at the end of the code. How about
<?php
$q = $_REQUEST["q"];
$q = strtolower($q)
$result = ""
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result
?>
To
<?php
$q = $_REQUEST["q"];
$q = strtolower($q);
$result = "";
if ($q === "foo") {
$result = "Correct";
} else {
$result = "Incorrect";
}
echo $result;
?>

Keyup Event in case of dot CO & COM url Shorten

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>

$_POST not returning a value

I've been searching for an answer to this for several days now, but if I missed the answer in another post, let me know.
I'm trying to get into Ajax, so I have a very simple form in my index.php, with separate php and javascript files:
index.php
<div id="ajax-test">
<form action="ajax/ajax.php" method="POST">
<textarea name="someText" id="some-text" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
main.js:
function getXMLHttpRequestObject() {
var temp = null;
if(window.XMLHttpRequest)
temp = new XMLHttpRequest();
else if(window.ActiveXObject) // used for older versions of IE
temp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
return temp;
}// end getXMLHttpRequestObject()
function loadDoc() {
var ajax = getXMLHttpRequestObject();
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
};
ajax.open("POST", "ajax/ajax.php", true);
ajax.send();
}
ajax.php:
<?php
print_r('\'' . $_POST['someText'] . '\' is what you wrote');
?>
Whenever I try to print, it prints: " '' is what you wrote " - what am I missing/not doing/doing incorrectly that isn't allowing me to access the content of someText? I've changed my naming convention, swapped from single quote to double quote, tried GET instead of POST, but nothing worked.
You can try to set a header request and also put the data inside the send. Here an example as like as-
ajax.open("POST", "ajax/ajax.php", true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send("someText="+document.getElementById('some-text').value);
This is probably beacuse of the error
Undefined index: someText in C:\xampp\htdocs\ssms\sandbox\ajax\ajax.php on line 3
You had a couple of issues with your code which i don't have time to list out now. This should work fine, plus i used the onkeyup() function to display the text live without even clicking on the submit button.
The Index File
<div id="ajax-test">
<form method="POST" onsubmit="return false;">
<textarea onkeyup="loadDoc()" name="someText" id="someText" placeholder="Type something here"></textarea>
<button type="button" onclick="loadDoc()">Submit</button>
</form>
<div id="ajax-text"></div>
</div>
<script type="text/javascript" src="main.js"></script>
The Main Javascript file
function _(x) {
return document.getElementById(x);
}
function ajaxObj ( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200) {
return true;
}
}
function loadDoc() {
var someText = _("someText").value;
var ajax = ajaxObj("POST", "ajax/ajax.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_('ajax-text').innerHTML = ajax.responseText;
console.log(ajax.responseText);
}
}
ajax.send("someText="+someText);
}
The PHP AJAX File
if(isset($_POST['someText'])){
$someText = $_POST['someText'];
echo "\"$someText\"" . ' is what you wrote';
exit();
} else {
echo "An error occured";
exit();
}

Chat system using Mysqli, PHP and AJAX is inserting blank message into Database

I've hit a brick wall in my chat system project and I have tried all day to find a solution. So here I am.
In the file insert.php I am trying to use $_REQUEST to get the value of the textarea from chat.php.
When I type something in and click send, a blank message is sent to the database.
After playing around with it, sometimes the webpage displays a "1" in the div element im trying to display the message in.
Any help would be very much appreciated thank you.
chat.php
<!DOCTYPE html>
<html>
<head>
<title>{ Chat App }</title>
<link rel = "stylesheet" href = "styles/style.css" media = "all" />
<script src="insert.js"></script>
<link href='https://fonts.googleapis.com/css?family=Rokkitt' rel='stylesheet' type='text/css'>
</head>
<body>
<form name = "form1">
<textarea name = "message"></textarea>
<br>
Send
<br>
<div id = "msg"></div>
</form>
</body>
</html>
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
insert.php
<?php
include("connection/connection.php");
global $con;
$msg = isset($_REQUEST['msg']);
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
$get_msg = "SELECT * FROM msg ORDER by id DESC";
$run_msg = mysqli_query($con, $get_msg);
while($row = mysqli_fetch_array($run_msg)){
echo $row['message'];
}
?>
The first problem is when you check for the null value, the function continues and submits the form if it is null or not.
insert.js
function submit(){
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
// stop the submit action
return;
}
var msg = form1.message.value;
var xmlhttp = new XMLHttpRequest(); // main object
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // data is ready
document.getElementById('msg').innerHTML = xmlhttp.responseText; // txtHint div now displays the data received by the request
}
};
xmlhttp.open('GET', 'insert.php', true);
xmlhttp.send();
}
The next problem is in the form handler, you are saving a boolean value isset($_REQUEST['msg']). Try this
insert.php
...
$msg = (isset($_REQUEST['msg']) && !empty($_REQUEST['msg']) ? $_REQUEST['msg'] : false;
if($msg){
// save data to database
...
}
or
...
if((isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
// message was submitted and it is not an empty string
$msg = $_REQUEST['msg'];
// save data to database
...
}else{
// do nothing
}
xmlhttp.open('GET', 'insert.php', true); try changing to xmlhttp.open('GET', 'insert.php?msg='+msg, true);
Hope it helps !
better to add "return" on error when you check if message is empty
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
}
so it could be
if(form1.message.value == ''){
document.writeln('Enter some text fool.');
return;
}
in submit() function
so the rest of function will not execute and empty message won't be sent.
and assign to variable message not the validation ))
if(isset($_REQUEST['msg']) && !empty($_REQUEST['msg'])){
$msg = $_REQUEST['msg']; //addiotionally this need escape
$insert = "INSERT INTO msg (message) VALUES ('$msg')";
$run_insert = mysqli_query($con, $insert);
}

Ajax failed to load contents from php file

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>

Categories

Resources