update database server with ajax and perl - javascript

I have set of code for updating a password in the table, here I'm using AJAX to update the password and get the popup screen on corresponding execution.When using that code with my application it is executing properly but I didn't get the output(password is not updated into table). I don't get any error either.
Html page Code
<html>
<head>
<div><IMG src="karvy.jpg" ALT="image"></div>
<script language="javascript" type="text/javascript">
//Browser Support Code
var xmlHttp;
function fetch_javaScript(usr,oldpassword,newpassword,repassword)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var usr = document.getElementById('usr').value;
var oldpassword = document.getElementById('oldpassword').value;
var newpassword = document.getElementById('newpassword').value;
var repassword = document.getElementById('repassword').value;
var url="changepwd1.pl";
url=url+"?usr=" + usr;
url=url+"&oldpassword=" + oldpassword;
url=url+"&oldpassword=" + newpassword;
url=url+"&repassword=" + repassword;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,false);
xmlHttp.send(null);
}
function stateChanged()
{
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
document.getElementById("ajaxDiv").innerHTML=xmlHttp.responseText;
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body bgcolor="#D2B9D3">
<form name='myForm'>
<center><table> <tr><td>
<div style="width:400px;height:280px;border:3px solid black;">
<center><h4>Please Enter your Password's</h4>
<p><b>User Name</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE=text NAME="usr" id = "usr" size = "15" maxlength = "15" tabindex = "1"/></p>
<p><b>Old Password:</b>&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="oldpassword" id = "oldpassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<p><b>Password:</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="newpassword" id = "newpassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<p><b>Re-Password:</b>&nbsp&nbsp&nbsp<INPUT TYPE=PASSWORD NAME="repassword" id = "repassword" size = "15" maxlength = "15" tabindex = "1"/></p>
<input type="submit" id="val" value="Submit" align="middle" method="POST" onclick="fetch_javaScript()"/><INPUT TYPE="reset" name = "Reset" value = "Reset"/>
<p>Main Menu <A HREF = login.pl>click here</A></p>
</center>
</div>
</td></tr></table></center>
</form>
<div id='ajaxDiv'>Your result will display here</div>
<!--<div id="myDiv"></div>-->
</body>
</html>
Perl Code
#!/usr/bin/perl
use DBI;
use strict;
use CGI;
my $cgi = CGI->new;
print $cgi->header;
print $cgi->start_html("Password Form");
print "Content-type: text/html\n\n";
my $request;
######################################## Query String
if ($ENV{'REQUEST_METHOD'} eq "GET")
{
$request = $ENV{'QUERY_STRING'};
}
elsif ($ENV{'REQUEST_METHOD'} eq "POST")
{
read(STDIN, $request,$ENV{'CONTENT_LENGTH'}) || die "Could not get query\n";
}
#$request="usr=sairam&oldpassword=password123&oldpassword=123456&repassword=123456";
my $j=0;
my ($i,#update_value,#value);
my #parameter=split(/&/,$request);
for $i (#parameter)
{
#value=split(/=/, $i);
$update_value[$j] =$value[1];
$j++;
}
my $user=$update_value[0];
my $oldpward=$update_value[1];
my $newpward=$update_value[2];
my $repward=$update_value[3];
#$user = $_SESSION['username'];
if ($user)
{
## Database Connectivity
my $DSN = q/dbi:ODBC:SQLSERVER/;
my $uid = q/ivr/;
my $pwd = q/ivr/;
my $DRIVER = "Freetds";
my %attr = (PrintError => 1,RaiseError => 1,);
my $dbh = DBI->connect($DSN,$uid,$pwd,\%attr) or die $DBI::errstr;;
my $sth=$dbh->prepare("select password from rpt_account_information where username='$user'") or die("Query didn't work");
$sth->execute();
my $oldpassworddb=$sth->fetchrow();
# check pass
if ($oldpward==$oldpassworddb)
{
# check twonew pass
if ($newpward==$repward)
{
#success
#change pass in db
if (length($newpward)>10||length($newpward)<4) #Here is the code
{
print "<script>alert('Password must be betwwen 4 & 10')</script>";
}
else
{
my $p_update = $dbh->prepare("UPDATE rpt_account_information SET password=? WHERE username=?");
$p_update->execute($newpward,$user);
#session_destroy();
print 'Your pass has benn changed.Return to the main page';
}
}
else
{
print "<script>alert('New Pass does not match')</script>";
}
}
else
{
print "<script>alert('Old Pass does not match')</script>";
}
}
This is my complete code but I'm not able to find out error or output
Please help me...

Assigning a value to innerHTML that contains a <script> element won't cause that script to be executed.
As a work around, you could parse the JavaScript out of it in JS and then eval it, but you would be better off dealing in structured data (e.g. JSON) and leaving your presentation logic to JavaScript already in the page.

Related

AJAX logic not working

I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});

Where to put a loading icon in this ajax form please anyone tell me?

My code is like this i took it from a tutorial website dont remember where please tell me where to put a loading icon in this huge junk of code i dont understand.
Please show me an example via jsfiddle or anywhere else.
<script language = "javascript" type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name = 'myForm'>
Max Age: <input type = 'text' id = 'age' /> <br />
Max WPM: <input type = 'text' id = 'wpm' />
<br />
Sex: <select id = 'sex'>
<option value = "m">m</option>
<option value = "f">f</option>
</select>
<input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
First, check this out for more info on ready states.
I'd put a loading just before ajaxRequest.open("GET", "ajax-example.php" + queryString, true); and remove it on if (xmlhttp.readyState==4.
1.
So add HTML where you'd like the loading icon to appear:
<span id="loading"></span>
2.
Then just before ajaxRequest.open... insert loading image:
document.getElementById("loading").innerHTML = '<img src="loading.gif" />';
3.
And inside if (xmlhttp.readyState == 4 put:
document.getElementById("loading").innerHTML = '';

post a form using ajax and returning the results to span or div

I would like to submit a form using ajax and return the results to the same page using innerHTML. But it seems the input value on the form is not getting passed to the action which is a php.
Here is my html form
<form id="check" method="POST" onsubmit="return checkFunction();">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="submit" value="Check" onclick="return checkFunction();"/>
</p>
</form>
This is where I would like the results returned on the same page
<span id="results"></span>
And this is how I put together the ajax call
function checkFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("results").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST","run.php",true);
ajaxRequest.send();
}
And this is how the php action file put together
<?php
$storeNum = $_POST['storenum'];
echo "<pre>Store number: " . $storeNum . "</pre>";
$pingresult = shell_exec("./ping_isp.sh $storeNum");
echo "<pre>$pingresult</pre>";
if (strpos($pingresult, 'ISP was unreachable') == true) {
echo '<script language="javascript">';
echo 'alert("ISP not available")';
echo '</script>';
die();
}
echo "<br>";
?>
If I use directly the php on the form as action let say like below it works perfectly
<form id="check" method="POST">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="submit" value="Check" formaction="run.php"/>
</p>
</form>
But this will return the results on another page. I would like to get the results returned on the same page. Hope you guys can help me out on this.
I agreee with #chris85, this could be dangerous to do. In any event, to answer your question I've made the changes to your code that I believe you need...
function checkFunction(){
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("results").innerHTML = ajaxRequest.responseText;
}
}
var storevalue = document.getElementByID("storenum").value;
ajaxRequest.open("POST","run.php",true);
ajaxRequest.send("storenum=" + storevalue);
}
Please forgive me if I've made any slight mistakes in coding, this is untested and it's possible I made a typo that I've missed.
EDIT: I had a little more time this morning than yesterday, so I took your code and reworked it a bit. The version below now works and should give you the result you're looking for.
function checkFunction(){
var xmlhttpmod;
var storevalue = document.getElementByID("store").value;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttpmod=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttpmod=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpmod.onreadystatechange=function() {
if (xmlhttpmod.readyState==4 && xmlhttpmod.status==200) {
// console.log(xmlhttpmod.responseText);
document.getElementById("results").innerHTML = xmlhttpmod.responseText;
}
}
xmlhttpmod.open("POST","test.php",true);
xmlhttpmod.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttpmod.send("storenum="+storevalue);
}
try this and post your results please
<form id="check" method="POST">
<p>
<label for="store">Type Store Number to check:</label>
<input type="text" id="store" name="storenum" maxlength="4"/>
</p>
<p>
<input type="button" value="Check" id="submitMyForm"/>
</p>
<div id="response"></div>
</form>
your php file:
<?php
if($_POST){
$required = array('storenum');
$error = false;
foreach($required as $key){
if(empty($_POST[$key])){
$error = true;
}
}
if(!$error){
// process data or whatever you need
}
else{
echo 'empty field error';
}
}
else{
header("Location: ../login.php");
}
and your ajax
$('#submitMyForm').on('submit', function(){
var thisForm = $(this),
url = thisForm.attr('action'),
type = thisForm.attr('method'),
data = {};
thisForm.find('[name]').each(function(index, value){
var thisField = $(this),
name = thisField.attr('name'),
value = thisField.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response').hide().html(response).fadeIn(700);
},
error: function(){
$('#response').hide().html('<span class="label label-danger">OcurriĆ³ un error desconocido</span>').fadeIn(700);
}
});
return false;
});

Form action submit in ajax and jQuery?

I have created 3 radio buttons:
Change Password - Change Name - Delete Account
When I select one of them it shows me a form that does something... but the problem is when I started to click submit button on the showing form it redirects me to another page, not the page I selected on action property in form
For example:
<form action = 'forget_pass.php' method = 'POST'>
when I click on submit button it should redirect me to page (forget_pass.php) but it redirects me to another page on my big project that I am working on currently.
My code that contains radio buttons:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("results").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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_form.php?z="+str,true);
xmlhttp.send();
}
}
</script>
<form class = "form-horizontal">
<label><p style="color:red;">
<input type = "radio" name = "select" value = "pass" onChange="showUser(this.value)"> Change Password
<input type = "radio" name = "select" value = "name" onChange="showUser(this.value)"> Change Name
<input type = "radio" name = "select" value = "account" onChange="showUser(this.value)"> Delete Account
</p></label>
</form>
<div id = "results"> </div>
My code that showing the forms(get_form.php):
<?php
$z = $_GET['z'];
if($z == "pass")
{
// form
}
else if ($z == "account")
{
// form
}
else if($z == "name")
{
// form
}
?>

onkeyup function only firing once

I need the onkeyup to fire more than once, but it seems to be only firing once!
When I enter something into the input box, it searches, but then whenever I backspace and search something else, the div stay's the same..
Here is my code:
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'dam_search.php?dam_text=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
Here is dam_search.php
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
ALSO: I am wondering how I can put the return of the name's it has searched into a dropdown from the input box instead of into the div, so when I click on one of the names, it auto fills the input box.
Thank you!
Still not sure about your issue with the keyup only firing once per page-load. That's very hard to speculate reasonably on without seeing more code. Never-the-less, here's an example I just threw together of how you can present the returned data in a more useful way.
The code requires that you download the AjaxRequest library I mentioned in an earlier comment.
(http://ajaxtoolbox.com/request/)
Here, I demo a few principles.
Arranging the data into a php class
constructing an array of instances of this class
returning this array as JSON
catching the JSON text and turning it back into an object in JS
Processing the data
I've given 2 very simple example - the first simply loads all filenames in the current directory (that holds jsonDir.php) into a select element. Choosing a filename results in it being copied into a text input next to the button.
The second, only retrieves names of png files. It chucks them all into a select element too. This time however, when an item is selected it is used as the src for an image. In each case the filenames are only grabbed if/when the corresponding button is pressed. There's a bit of redundant/otherwise crappy code I could have done better, but after 20 hours awake, I'm ready for bed!
Hope it's useful for you. Any questions, just ask. :)
1. jsonDir.php
<?php
class mFile
{
public $name, $time, $size;
}
if (!isset($_GET['wildcard']))
$wildCard = "*.*";
else
$wildCard = $_GET['wildcard'];
foreach (glob($wildCard) as $curFilename)
{
$curFileObj = new mFile;
$curFileObj->name = $curFilename;
$curFileObj->time = date("d/m/Y - H:i", filectime($curFilename));
$curFileObj->size = filesize($curFilename);
$fileArray[] = $curFileObj;
}
printf("%s", json_encode($fileArray));
?>
2. readDir.html
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script/ajaxRequestCompressed.js'></script>
<script>
function byId(e){return document.getElementById(e);}
function newEl(tag){return document.createElement(tag);}
function myGetAjaxResponseWithCallback(url, target, callbackFunc)
{
AjaxRequest.get(
{
'url':url,
'onSuccess':function(req){ callbackFunc(req.responseText, target); }
}
);
}
function getResults1()
{
var url = "jsonDir.php";
var target = byId('resultsDiv');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived1);
}
function getResults2()
{
var url = "jsonDir.php?wildcard=*.png";
var target = byId('resultsDiv2');
myGetAjaxResponseWithCallback(url, target, jsonDataReceived2);
}
function jsonDataReceived1(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mStr = "There were " + resultObject.length + " records returned" + "<br>";
var mSel = newEl("select");
mSel.addEventListener('change', doAutofill, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = mStr;
targetContainer.appendChild(mSel);
}
function jsonDataReceived2(responseText, targetContainer)
{
var resultObject = JSON.parse(responseText);
targetContainer.innerHTML = "";
var mSel = newEl("select");
mSel.addEventListener('change', showSelectedImg, false);
var i, n = resultObject.length;
for (i=0; i<n; i++)
{
var curRecordOption = new Option(resultObject[i].name, i);
mSel.appendChild(curRecordOption);
}
targetContainer.innerHTML = '';
targetContainer.appendChild(mSel);
}
function doAutofill(e)
{
var curSelIndex = this.value;
var curText = this.options[curSelIndex].label;
byId('autofillMe').value = curText;
}
function showSelectedImg(e)
{
byId('previewImg').src = this.options[this.value].label;
}
</script>
<style>
img
{
border: solid 2px #333;
}
</style>
</head>
<body>
<button onclick='getResults1()'>Get *.* dir listing</button> <input id='autofillMe'/>
<div id='resultsDiv'></div>
<hr>
<button onclick='getResults2()'>Get *.png dir listing</button> <img id='previewImg' width='100' height='100'/>
<div id='resultsDiv2'></div>
</body>
</html>
Found out my problem. The query wasn't correctly being processed!
I had the variable $dam_text as the LIKE statement, when it should have been $dam:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
$dam = $_GET['dam_text'];
getSuggest($text);
}
function getSuggest($text) {
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam_text%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
Also, the variable $dam wasn't being submitted inide the function, so I moved it from the 'if' statement, into the function:
<?php
//connect to db stuff here
if (isset($_GET['dam_text'])) {
getSuggest($text);
}
function getSuggest($text) {
$dam = $_GET['dam_text'];
$sqlCommand = "SELECT `name` FROM `table1` WHERE `name` LIKE '%$dam%'";
$query = mysql_query($sqlCommand);
$result_count = mysql_num_rows($query);
while ($row = mysql_fetch_assoc($query)) {
echo $row['name'].'<br />';
}
}
?>
The above code works perfectly! Turns out it wasn't onkeyup after all! Thanks for all your help!
OnKeyUp will only fire once per event. pressing 'A' 'B' and 'C' will result in three calls to suggest1();
To make sure your browser is working correctly try this
<script type="text/javascript">
function suggest1() {
document.getElementById('myDiv').innerHTML = document.getElementById('dam').value;
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>
You should see the div change for every keystroke that occurs in the input.
There is two many unknowns for me to directly point at your actual issue.
Your PHP will output nothing for a zero entry query, and will only output 1 item if you query LIKE only matches one thing. I think your problem lies elsewhere, an not with onkeyup
T test to onkeyup on your system/browser:
Try adding some debug header like echo strlen($text).'<br />'; to your PHP file. You should see the number change with out relying on your SQL query for every key press that adds or deletes text (that includes the backspace key).
Your code looks fine. And runs fine for me using the public HTTP GET echo service at http://ivanzuzak.info/urlecho/
Swapping out your PHP for the echo service works fine (with a bit of a typing delay)
<script type="text/javascript">
function suggest1() {
var dam_text = document.getElementById('dam').value;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('MicrosoftXMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML = xmlhttp.responseText;
}
}
var target = 'http://urlecho.appspot.com/echo?body=' + dam_text;
xmlhttp.open('GET', target, true);
xmlhttp.send();
}
</script>
<input type="text" name="dam" id="dam" onkeyup="suggest1();"><br />
<div id="myDiv"></div>

Categories