How to make sure that I can scroll up in AJAX chat - javascript

I am building a vanilla JS, AJAX chat (so no jQuery or other toolkits). The messages are loaded via AJAX and put in a div that uses overflow-y: scroll; so you can scroll through all the messages.
Because the latest messages appear at the bottom I have a scrollDown() function that scrolls to the end of the div:
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
}
The problem is that I can't scroll up. If I do that I will get to the bottom again. This is because on every ajax call I scroll down. But how can I make sure that if an user is scrolled up in the div (so he/she is reading past messages) that it doesnt scroll down when AJAX gets updated.
I already tried some things with div.scrollHeight, div.scrollTop but unfortunately it didn't work. I also did a lot of Google searches but no luck either and most them were jQuery though. Here is my code;
<script type="text/javascript">
getBerichten();
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
function doWork(id, user_id) {
nieuwbericht = getHTTPObject();
if (nieuwbericht != null) {
if( document.getElementById('bericht').value != "")
{
nieuwbericht.open("GET", "ajaxberichten.php?id=" + id + "&user_id=" + user_id + "&bericht="
+ document.getElementById('bericht').value, true);
nieuwbericht.send(null);
document.getElementById("bericht").value = "";
}
}
}
function setOutput()
{
if(httpObject.readyState == 4){
document.getElementById('berichten').innerHTML = httpObject.responseText;
bericht = document.getElementById('chatbox');
scrollDown();
setInterval(getBerichten(),1000);
}
}
function getBerichten()
{
httpObject = getHTTPObject();
if (httpObject != null)
{
httpObject.open("GET", "ajaxgetberichten.php?id=<?php echo $_GET['id'] ?>", true);
httpObject.send(null);
httpObject.onreadystatechange = setOutput;
}
}
function scrollDown()
{
var objDiv = document.getElementById("chatbox");
objDiv.scrollTop = objDiv.scrollHeight;
}
</script>
<div class="postbox">
<div class="post">
<div class="chatbox" id="chatbox">
<div id="berichten"></div>
</div>
<form method="post" action="">
<textarea name="bericht" id="bericht"rows="20" cols="85"> </textarea>
<input name="verstuur" type="button" onclick="doWork(<?php echo $_GET["id"] ?>, <?php echo $user_id ?>);" value="Verstuur"/>
</form>
</div>
</div>
Could somebody please tell me how to fix this without a JS toolkit like jQuery?
Thanks

Related

Do a javascript redirect after an ajax call

I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.

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)
})
});

Progress bar goes straight to 100% on first upload only, following uploads show as expected

Problem:
When I start up any Browser, it opens up with its default web page, I open a session to my
Test File Upload with Progress bar Web Application in that Tab, or that same Web App. in a new Tab. When I
start the first file upload, it shows the Progress bar to go straight to 100% even though the file is still
uploading. If I then do the file upload again, it works as expected, the progress bar shows the file being
loaded, eg 20%, 43%, 80%, 98% then Done.
I am using the example that is published at:-
https://www.sitepoint.com/tracking-upload-progress-with-php-and-javascript/
I have modified it slightly in an effort to find out what is going on.
This problem occurs on my Web Site which is on the Internet and on my Local Server.
Both systems are LINUX, using Apache2. The Web Site on the Internet is using PHP 5.6.30. My local server
is using PHP 7.1.5.
This same problem can be reproduced when using a Cellphone running Safari, Chrome, or FireFox.
So this looks like a Server based issue or some coding issue I have either at the Client
or Server end.
I use this type of code to upload Video files and my work around is to assume that the file
will not be fully uploaded until at least after the first progress percent loaded calculation. If I
get the '100' reply on the first pass I assume that the progress bar reading is wrong and suggest
the the file upload should be tried again. The second upload always works. In my case the maximum
size allowed for the video file 28MB.
Can anybody assist with this problem?
Below is a copy of my two PHP Web Pages.
File: progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
{
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else
{
echo "100";
}
?>
File: upload2.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
// move_uploaded_file()
$folder = "tmp/";
//upload the file
move_uploaded_file($_FILES["userfile"["tmp_name"], "$folder" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style>
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="Message"></div>
<form action="" method="POST"
id="form_60" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="form_60"
name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
<!script type="text/javascript" src="upload2.js"></script>
<script type="text/javascript">
var FirstTime = 'Y';
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php", false); // was GET
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("Message").innerHTML = response + "%";
alert(response);
if (response < 100) {
FirstTime = 'N'
setTimeout("sendRequest()", 1000);
}
else {
alert(response);
toggleBarVisibility();
if (FirstTime == 'N')
{
document.getElementById("Message").innerHTML = "Done.";
}
if (FirstTime == 'Y')
{
document.getElementById("Message").innerHTML = "Error.";
alert('System error, please try again.')
}
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("form_60").onsubmit = startUpload;
})();
</script>
</body>
</html>
I have now found a workaround, which is listed below. It involves doing a Dummy request from a startup page in my application. In my case I use the Login Web Page to put the Dummy code.
<script type="text/javascript">
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php", false); // was GET
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http)
{
var response;
if (http.readyState == 4)
{
response = http.responseText;
if (response < 100)
{
setTimeout("sendRequest()", 1000);
}
}
}
function startUpload() {
setTimeout("sendRequest()", 1000);
}
window.onload = function() {
startUpload();
}
</script>
Now that I have learnt a bit more about Session Variables it seems that to follow the rules I should have put:-
session_start();
at the start of the upload2.php web page, as this is where the variable information is coming from in the first instance. This then works fine.
It looks as though the session is not reading in the if statement at the beginning. You just echo out 100% if the Session doesn't exist. If you ammend this part:
Progress.php
<?php
session_start();
$key = ini_get("session.upload_progress.prefix") . "form_60";
if (!empty($_SESSION[$key]))
{
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else {
$_SESSION[$key]["bytes_processed"] = 0;
}
?>
It shouldn't jump straight to 100% because the Session will be active at this point rather than after the first upload. Not tested but worth a try, I'll stick this code on my test server when I get a chance to do a proper test if you don't beat me to it!

Generated anchor links in ajax not working

Problem:
I have a which is filled via Ajax. There are some local anchors which are created in this table. When an anchor is clicked, it is supposed to turn a which is hidden to visible and scroll to it automatically. All of this is working when I am filling my by hand (visibility + scroll), but not at all when the is filled via Ajax.
I have the following structure in my index.php file:
<section id="section1">
<table></table>
</section>
<section id="section2>
(this section is hidden via CSS)
</section>
<!-- When the link "More infos" is clicked -->
<script>
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
</script>
<!-- Ajax call -->
<script language="JavaScript">
function createInstance()
{
var req = null;
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e)
{
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e)
{
alert("XHR not created");
}
}
}
return req;
};
function storing(data)
{
var element = document.getElementById('banques');
element.innerHTML = data;
}
function submitForm()
{
var req = createInstance();
var montant = document.getElementById("montant").value;
var mois = document.getElementById("selectMois").value;
var taux = '<?php echo $taux; ?>' ;
var data = "taux=" + taux + "&montant=" + montant+ "&mois=" + mois+"&tag=" + 1;
req.onreadystatechange = function()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
storing(req.responseText);
}
else
{
alert("Error: returned status code " + req.status + " " + req.statusText);
}
}
};
req.open("POST", "fonction/table.php", true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.send(data);
}
</script>
The "Simulate" link calls a php file in ajax which will load the table.
Here is the php file called in Ajax :
<?php
include('BDD.php');
echo' <tr>
<th></th>
<th>Banque</th>
<th>Taux</th>
<th>Frais</th>
<th>Mensualité</th>
<th>Plus d\'infos</th>
</tr>';
$tag=1;
$sql="select * from banque where BAN_change=0 and BAN_tag=".$_POST['tag']." ORDER BY BAN_Ordre";
$select=$bdd->query($sql);
$result=$select->fetchAll();
$nb=count($result);
if ($nb!=0){
foreach($result as $value){
$taux=$_POST['taux']+$value['BAN_Taux_Credit'];
$mensu=$_POST['montant']/$_POST['mois'];
$mensu+=$mensu*$taux/100;
echo'<tr>';
echo'<td><img width="50" height="20" src="img/'.$value['BAN_Id'].'/img.jpg" /></td>';
echo'<td>'.$value['BAN_Nom'].'</td>';
echo'<td>'.$taux.'</td>';
echo'<td>'.$value['BAN_Frais'].'</td>';
echo'<td>'.$mensu.'</td>';
echo('<td>More infos</td>');
echo'</tr>';
}
}
?>
Summary: When the user clicks on "More infos", the #section2 is supposed to appear and the browser window scrolls to it. Now this is working perfectly when I fill the by hand. Then the #section2 is showing and the browser is scrolling to the #section2. When I am doing it via Ajax, the anchors are not working anymore.
Thanks
Because events do not magically get attached when you add new ones
$('.moreInfos').click(function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
Your code needs to use event delegation
$(document).on("click", '.moreInfos', function() {
if ($('#section2').is(':hidden')) {
$('#section2').slideDown('slow');
}
});
This maybe due to the HTML not being loaded into the DOM. Please try using:
$(document).on('click', '.selector', function() {
alert("Working");
});
"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page."
If this works then you can fine tune it afterwards.
Regards,

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