i need to check email availablity for this task. while i enter any email address, after i press tab it should check in the database and return whether this email are already exist or not.
but this routine gives exact output as what i expect while checking it in console. but the error message didn't written on my html page. can any one help me? thanks in advance.
HTML coding
<div class="txtinputcomp">
<input name="frmVisitorEmail" id="frmVisitorEmail" onblur="checkEmail(this.value);" class="emailbox" required="required" value="<?php echo $_POST['frmVisitorEmail']; ?>" placeholder="Visitor Email" type="email" />
</div>
<div class="emptytxtcomp">
<span id="errorEmail" class="errorStyle"></span>
</div>
FindEmail.php
<?php
include("includes/config.php");
$strEmail = $_GET["email"];
$strData = doCheckEmail($strEmail);
if($strData!=0) {
echo "<script type='text/javascript'>
document.getElementById('errorEmail').innerHTML = 'Email address are already exist!';
return false;
</script>";
} else {
echo '<script type="text/javascript">
document.getElementById("errorEmail").innerHTML = "";
</script>';
}
?>
AJAX script
function checkEmail(str)
{
var xmlhttp;
if (str.length==0) {
document.getElementById("frmVisitorEmail").innerHTML="";
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("frmVisitorEmail").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","findEmail.php?email="+str,true);
xmlhttp.send(null);
}
Function
function doCheckEmail($strIdent)
{
$strSelectsSql = "Select count(*) as TotalCnt from tbl_visitor Where visitor_email='".$strIdent."' ";
$strSelectsResult = SelectQry($strSelectsSql);
return $strSelectsResult[0][0];
}
function SelectQry($Qry) {
$result = mysql_query($Qry) or die ("QUERY Error:".$Qry."<br>".mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
return;
} else {
$row = array();
$record = array();
while ($row = mysql_fetch_array($result)) {
$record[] = $row;
}
}
return MakeStripSlashes($record);
}
This line won't run the script that the PHP is echoing:
document.getElementById("frmVisitorEmail").innerHTML=xmlhttp.responseText;
In order to execute dynamically-added Javascript, you have to use createElement to create a script element.
Instead, I suggest that the PHP just return the error message, not a script block. So it should be:
if($strData!=0) {
echo "Email address are already exist!";
} else {
echo "";
}
Then the Javascript would be:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
document.getElementById("errorEmail").innerHTML=xmlhttp.responseText;
}
}
Related
I am using this example to run an ajax data query from an mysql db, that returns a table.
This is working fine when text is manually typed into this input form eg:
But the search form has an autocomplete jquery script that will help the user along. When a value is chosen from the dropdown autocomplete values, the onchange event isn't recognized, no table shows.
My question is, how would I put a button at the end of the search form, to change this to 'onclick' event, rather than 'onchange'? The hurdle I am facing is that the input for 'client_address' is part of a larger form, and clicking submit on any button causes the page to try submit the entire form.
create_wt.php:
// autocomplete
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
source: 'backend_search_addressWT.php'
});
});
</script>
// retrieve data in table
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<div class="form-group <?php echo (!empty($client_address_err)) ? 'has-error' : ''; ?>">
<label>Address</label>
<div class = "input-group">
<input id="clientsearch" type="text" name="client_address" onchange="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
<!---<span class="input-group-btn">
<button class="btn btn-success" value="submit" id="ajaxbtn" type="submit">Get Client Info</button>
</span> -->
</div>
<br><div id="txtHint"><b>Person info will be listed here...</b></div>
<span class="help-block"><?php echo $client_address_err;?></span>
</div>
ajax_get_client_info.php:
<?php
require_once 'config.php';
$q = trim($_GET['q']);
$query = $mysqli->query("SELECT * FROM client WHERE client_address LIKE '%".$q."%'");
//$data = array();
//while ($row = $query->fetch_assoc()) {
// $data[] = ($row);
//}
//echo json_encode($data);
echo "<table>
<tr>
<th>client_id</th>
<th>Client Name</th>
<th>Phone Number</th>
</tr>";
while($row = mysqli_fetch_array($query)) {
echo "<tr>";
echo "<td>" . $row['client_id'] . "</td>";
echo "<td>" . $row['client_name'] . "</td>";
echo "<td>" . $row['client_phone'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
EDIT:
create_wt:
<script type="text/javascript">
$(function() {
$( "#clientsearch" ).autocomplete({
select: function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q="+str,true);
xmlhttp.send();
}
}
}
{
source: 'backend_search_addressWT.php'
});
});
</script>
According to jQuery UI Autocomplete documentation:
http://api.jqueryui.com/autocomplete/#event-select
the select event of the autocomplete input does not accept the user's input as an argument but has 2 other: event, ui.
So you are trying to access the value: ui.item.value that is the selected item's value.
So that must be your problem.
CBroe has the same answer in the comments.
....
function getHint(value) {
if ((value !== "") && (typeof value !== 'undefined')) {
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 ((this.readyState == 4) && (this.status == 200)) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","ajax_get_client_info.php?q=" + value, true);
xmlhttp.send();
return true; // return true to accept the selection of the user
} else {
document.getElementById("txtHint").innerHTML = "";
$(this).autocomplete( "close" ); // Close the autocomplete popup manual because by returning false negates the selection but it does not close the popup.
return false; // return false to negate the selection of the user
}
}
$( "#clientsearch" ).autocomplete({
select: function showUser(event, ui) {
return getHint(ui.item.value);
},
change: function showUser(event, ui) {
return getHint(ui.item.value);
},
{
source: 'http://www.example.com'
}
});
....
Be sure to read the documentation so you know how to treat this case from the start.
Hope this helps.
Change onchange in input box to onkeyup, that should solve, onchange is mainly used for radio buttons and checkboxes.
<input id="clientsearch" type="text" name="client_address" onkeyup="showUser(this.value)" class="input-group form-control" value="<?php echo $client_address; ?>" placeholder="Search by address..." style="width: 500px;">
Use a input type button:
<input type="button" name="" id="">
and use its click event. Input type will not submit the form.
I have a problem with my ajax php coding.
The problem is when the user enter their password to login ,the live checking function output only shown blank in select box below, not the data from database.
Below is my code:
Login.php
username:<input type="text" class="name" id="uname" placeholder="enter your username here"><br>
password:<input type="password" class="pass" id="pword" placeholder="password here"><br>
<div id="txt">
responsibility:<select id="opti">
<option value=""> Select your responsibility</option>
</select><br></div>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txt").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txt").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","dblogin.php?q="+str,true);
xmlhttp.send();
}
}
document.getElementById('pword').addEventListener("keyup", function(str) {
showUser(str);
}, false);
</script>
Dblogin.php
<?
$q=intval($_POST["pword"]);
require ("config.php");
$link=mysqli_connect($host,$user,$pass,$db);
$query="select responsibility from testing where password = '".$q."'";
$result=mysqli_query($link,$query);
if($result){
?>
<form>
responsibility:<select id="opti">
<?
while($row=mysqli_fetch_array($result))
echo"<option value='$row[1]'>$row[1]</option>";
?>
</select>
<input type=submit value ="submit">
<?
}
else
{
?>
Error:No Data Found
<?
}
?>
config.php
<?
$host="localhost";
$db="logindb"
$user="root"
$pass="";
?>
the ajax function is work, but the database data not shown. Can anybody tell me what wrong with my coding.
I am a beginner in jquery and ajax. I'm trying to get google like suggestion while typing in the textbox. However I've tried for hours and still can't get to view the suggestion as a list and autofill the textbox while selecting text from the list. Here is what I've tried so far.
The php file-
$conn = new mysqli("host", "user", "pass", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT data1, data2 FROM table";
$result = $conn->query($sql);
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
while ($row = $result->fetch_assoc()){
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($row as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
}
else {
$hint .= "</br> <a href='#'>$name </a>";
}
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","getdb.php?q="+str,true);
xmlhttp.send();
}
The html file-
<p><b>Start typing a name in the input field below:</b></p>
<div>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
<div id="livesearch">
</div>
</div>
Another problem is the first suggestion from the list isn't appearing as a link like rest of the suggestion.
Screenshot
How can I list my suggestions properly and how can I can fill the textbox when a user selects text from the list. Pl's help!
Solved it myself few days ago. Here is what the code looks like so far.
The php file-
$q = $_REQUEST["q"];
//$hint = "";
$sql = "SELECT data FROM tables WHERE Firstdata LIKE '%" . $q . "%' OR Lastdata LIKE '%" . $q ."%'";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()){
$FirstData =$row['Firstdata'];
$LastData =$row['Lastdata'];
$ID=$row['ID'];
//-display the result of the array
if ($q !== "") {
echo "<li class="."list-group-item".">"
. "<a href=\"phpfile.php?id=$ID\">" .
$FirstData ." ". $LastData . "</a>
</li>";
}
}
The Javascript code-
function showHint(str) {
if (str.length == 0) {
document.getElementById("livesearch").innerHTML = "";
document.getElementById("livesearch").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="0px solid";
}
}
xmlhttp.open("GET","php/ajaxphpfile.php?q="+str,true);
xmlhttp.send();
}
The html file-
<input type="text" class="search-query form-control" onkeyup="showHint(this.value)" id="type" name="name"placeholder="Search" />
<button type="submit" name="submit" value="oldsearch" class="btn btn-danger" type="button"></button>
<div id="livesearch"></div>
This code is inside a JavaScript function triggered by the onsubmit event of a form.
var username = document.register.username.value;
var phpUsernameFree = <?php
$username = "<script>document.write(username)</script>";
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo 1;
};
?> ;
if( phpUsernameFree == 0){
toggleNew('usernameAlreadyExists', 1);
usernameCounter = 1;
}
I want that if the username already exists in the database a window is shown telling the user that the username already exists.
I've tried deleting all of the php code and simply replacing it by 'echo 1' or 'echo 0', and that worked, so I know that code executes.
I think there's a problem in the attempt to read information from the database.
EDIT:
Okay I've tried doing this with Ajax, didn't work so far. I downloaded jQuery and I'm trying out this code now:
usernameTaken = checkUserExistence(username, 'username');
if( usernameTaken == 1){
toggleNew('usernameAlreadyExists', 1);
usernameCounter = 1;
}
function checkUserExistence(str, type){
var dataString = 'str=' + str + '&type=' + type;
if($.trim(str).length>0 && $.trim(type).length>0){
$.ajax({
type: "POST",
url: "existance.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#submit").val('Sending...');},
success: function(data){
if(data){
return 1;
}else{
return 0;
}
}
});
}
return false;
}
my existance.php looks like this:
<?php
*include connection to database here*
$data = $_POST["data"];
$type = $_POST["type"];
$resultUsers = mysql_query("SELECT * FROM users WHERE username = '$data' ") or die(mysql_error());
if( mysql_num_rows($resultUsers) == 1 ){
echo 1;
}
?>
Currently what happens when using this code is, when I press the submit button, the value changes to 'Sending...' as in the beforeSend attribute, but nothing else happens.
You need AJAX to do that, if you do not want to use Jquery.
Something like this:
<script>
function Login(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("Msg").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "Login.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
Login.php:
$username = $_REQUEST["q"];
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo "User free";
}else{
echo "User exist";
}
something like that, don't work but is an idea.
The best way is using ajax. you should do something like this:
$("#inputId").keyUp(function(){
//This event, raised when the textbox value changed
//inside this event, you can call ajax function and check user existance and if result is false you can disable the submit button
});
In stead of submit button use normal button, submit form after ajax response depending on the response value.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
function checkUserExistence(){
var username = document.register.username.value;
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest();} else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
phpUsernameFree = xmlhttp.responseText;
if( phpUsernameFree == 0){
alert("username Already Exists");
} else {
alert("username available.");
register.submit();
}
} else if(xmlhttp.status == 400) {
alert("There was an error 400");
} else {
alert("something else other than 200 was returned");
}
}
}
xmlhttp.open("GET", "service.php?username=" + username, true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="register" name="register" method="post">
<input type="text" name="username" id="username" value="check" />
<input type="button" id="save" name="save" value="Save" onclick="checkUserExistence();" />
</form>
</body>
</html>
<!-- service.php -->
<?php
$username = $_REQUEST["username"];
$resultTempUsers = mysql_query("SELECT * FROM tempUsers WHERE username = '$username' ") or die(mysql_error());
if( mysql_num_rows($resultTempUsers) == 0 ){
echo 1;
};
?>
Complete Dynamic drop down in PHP MySQL & AJAX with mysql Insert query works perfectly.
Code to insert date to MySQL table
<?php
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['state'];;
if(isset($_FILES['image'])) {
$errors=array();
$allowed_ext=array('jpg','png','jpeg','JPG');
$filename=$_FILES['image']['name'];
$name=stripslashes($filename);
$type=strtolower(end(explode('.',$filename)));
$size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
$errors[]= "<span class=\"notification n-error\">Extenstion Not Allowed</span>";
}
if($size > 1048576) {
$errors[]= "<span class=\"notification n-error\">File must be less then 2mb</span>";
}if(file_exists('../../images/a/gallery/'.$filename)) {
$errors[]= "<span class=\"notification n-error\">File $filname Already Exists in directory</span>";
}if(empty($errors)) {
if(move_uploaded_file($file_tmp, '../../images/a/gallery/'.$filename)) {
$insert="Insert into `my`.gallery(name,alttext,project,relation)VALUE('$name','$alttext','$project','$relation')";
//echo $insert;
$que=mysql_query($insert);
echo "<span class=\"notification n-success\">File $filname Uploaded Sucessfully</span>";
header('Refresh:3; url:gallery.php');
}
}else {
foreach($errors as $error) {
echo $error,'<br/>';
}
}
}
?>
AJAX Code
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Code for Second Drop Down or findsec.php
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
Thanks to Nick Wilde who helped me.
I'm presuming you mean when the value of the option for the second drop down is multiple words. If that is the case the problem is you are missing quotes; use this instead:
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
as the last three lines of your findsec.php