Running javascript code inside php doesn't work - javascript

this is my whole javascript code
what im trying to do here is loop through html table and look for checked checkbox and retrieve the data in every row of checked checkbox
but i need to run this is php.
<script type='text/javascript'>//<![CDATA[
$(window).load(function () {
$('#save').click(function () {
$('#dataTable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type="checkbox"]').is(':checked') ) {
//alert('You must fill the text area!');
var $row1 = $(this).closest("tr"), // Finds the closest row <tr>
$tdi = $row1.find("td:nth-child(1)");
$.each($tdi, function () { // Visits every single <td> element
var thirdrowval = $(this).text(); // Prints out the text within the <td>
//document.getElementById("signatoryid").value = thirdrowval
alert(thirdrowval);
});
}
});
});
});//]]>
</script>
and after reading in this site i found a way to do it and here is the code. but it doesn't run the javascript. i expect an alert to pop up. but it doesn't worked as expected
$row1 = "";
$row = "";
$thirdrowval = "";
$tdi = "";
echo "
<script type=\"text/javascript\">
$('#dataTable').find('tr').each(function () {
var row = $(this);
if (row.find('input[type='checkbox']').is(':checked') ) {
var $row1 = $(this).closest('tr'),
$tdi = $row1.find('td:nth-child(1)');
$.each($tdi, function () {
var thirdrowval = $(this).text();
alert(thirdrowval);
});
}
});
</script>
";

Try to include your table $('#dataTable') also in your php file.
I think javascript can't find the element that named #dataTable

in the line
if (row.find('input[type='checkbox']').is(':checked') ) {
you will have to escape the inner quotes ' it should be
if (row.find('input[type=\'checkbox\']').is(':checked') ) {
also you have to pay attention that variables in strings with double quotes like
echo "$row1";
will be replaced with the value of the php variable $row1. So in your example it will be replaced with an empty string. If this is not the exspected behaviour you can use single quotes:
echo '$row1';
this will print $row1

Related

AJAX live search is super slow

Edit: Im using XAMPP with built in Apache, vscode
I make a live search input(html>js>php>js>html) , it run smoothly at first key-in, but it's getting slower and slower when i delete and key-in again , wonder what's causing the delay and how to fix it.
And i have a question,
For this example , it is better to use jquery or pure javascript?
Thank you
html
<div>
<input type="text" class="search" placeholder="find..." autocomplete="off" autocapitalize="characters">
<div class="result"></div>
</div>
js
$(document).ready(function(){
$(document).on("keyup input",".search",function(){
var input = $(this).val();
var result = $(this).next(".result");
if(input.length){
$.get("table.php", {term: input}).done(function(data){
result.html(data);
});
} else{
result.empty();
}
});
});
php
<?php
$link = mysqli_connect("localhost", "root", "******", "crypto");
// Check connection
if($link === false){
die("ERROR: " . mysqli_connect_error());
}
if(isset($_REQUEST["term"])){
$coin = "show tables from crypto where Tables_in_crypto LIKE ?";
//prepare the statement
if($prepare = mysqli_prepare($link, $coin)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($prepare, "s", $param_term);
// Set parameters
$param_term = $_REQUEST["term"] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($prepare)){
$result = mysqli_stmt_get_result($prepare);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
echo "<p>" . $row["Tables_in_crypto"] . "</p>";
}
} else{
echo "<p>no result</p>";
}
} else{
echo "ERROR: $coin. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($prepare);
}
// close connection
mysqli_close($link);
?>
<script type="text/javascript" src="data.js"></script>
JavaScript
Don't use "keyup input", use just the "input" Event.
Trim $(this).val().trim() your input values, you don't want an empty space to trigger a search for data!
Cooldown! You don't want to perform an additional AJAX ($.get()) request while one is already on the way. Instead create a setTimeout throttle which - only once the user stopped typing for N milliseconds the request will be triggered.
A pseudocode logic to picture it is quite simple:
jQuery($ => { // DOM ready and $ alias in scope
const search = ($input) => {
const input = $input.val().trim(); // Trim your strings!
const $result = $input.next(".result");
if (!input) {
$result.empty();
return; // end it here
}
$.get("table.php", {term: input}).done((data) => {
console.log(data);
// Exercise for the reader:
// Make sure data is an Object
// create "<p>" elements with text and populate $result
});
};
let searchCooldown; // Search input cooldown
$(document).on("input", ".search", function() {
clearTimeout(searchCooldown); // clear occurring search timeout
searchCooldown = setTimeout(() => {
search($(this)); // will be triggered once user stops typing for 300ms
}, 300); // 300ms seems like a good typing timeout?!
});
});
No, you don't need jQuery. The Fetch API is mature enough.
PHP
Don't place <script> tags inside a PHP file — which its only job should be querying the data from a database and returning it.
Don't return HTML from PHP! That's a waste. You might want a PHP file to return JSON data instead - that way it can be used by your HTML page, your watch, fridge, etc. It's usually done using echo json_encode($result);. If you need to attach also an "error" property to your $result data JSON, do so.
I don't deserve a credit for myself because everything i find mainly is on stackoverflow (after many hours spent) just I model everything to my own needs and like to give back in return.
If your page has no pagination a nice and easy way to live search all the items in javascript by doing the following (the html code may not be related to the script):
-you need to use XPath in chrome dev tools, to get the element needed:(right click on an element node->Copy -> copy full xpath)
-lets say we want to search for all the <h2> text tags inside :
-in blade file we have products.blade.php:
<html>
<body>
<input type="text" placeholder="search" id="search" onkeyup="myFunction()"></input>
<ul id="myList" class="myList-class">
<li><h2>item 1<h2></li>
<li><h2>item 2<h2></li>
</ul>
//the script below is not related to the tags above, but just to give you an idea.
<script>
function myFunction() {
var lis = document.querySelectorAll('.columns-3.products.snip-ul > li');//get all the <li> tags, change it to your needs(get the value from Ranorex selocity extension in chrome).
var x = document.getElementById("search").value; //item to search for(textbox)
if (document.getElementById("search").value.length == 0) { //if nothing is typed in textbox get all the products back
lis.forEach(node=>node.setAttribute("style","display:flex")); // restore all the display attribute to flex
return;
}
for (var i = 1; li = lis[i-1]; i++) {
var searchTitles = ((document.evaluate('/html/body/div[1]/ul/li[' + i + ']/div/div[2]/a/h2/text()', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data);
//change the above xpath to your own needs : (document.evaluate('XPATH HERE', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue).data;
// li.parentNode.removeChild(li);
if (searchTitles.toLowerCase().includes(x.toLowerCase())) {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:flex";
} else {
document.evaluate('/html/body/div[1]/ul/li[' + i + ']', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.style = "display:none"; //hide all <li> tags
}
}
}
</script>

how to make javascript in to PHP

I have the following javascript code which I need to be executed in a PHP file.
I need to know how should I enter the php tags to this javascript code.
I am new to web programming.
The javascript used here is to export content in the html page to a .csv file.
<!-- Scripts ----------------------------------------------------------- -->
<script type='text/javascript' src='https://code.jquery.com/jquery-
1.11.0.min.js'></script>
<!-- If you want to use jquery 2+: https://code.jquery.com/jquery-2.1.0.min.js -->
<script type='text/javascript'>
$(document).ready(function () {
console.log("HELLO")
function exportTableToCSV($table, filename) {
var $headers = $table.find('tr:has(th)')
,$rows = $table.find('tr:has(td)')
// Temporary delimiter characters unlikely to be typed by
keyboard
// This is to avoid accidentally splitting the actual
contents
,tmpColDelim = String.fromCharCode(11) // vertical tab
character
,tmpRowDelim = String.fromCharCode(0) // null character
// actual delimiter characters for CSV format
,colDelim = '","'
,rowDelim = '"\r\n"';
// Grab text from table into CSV formatted string
var csv = '"';
csv += formatRows($headers.map(grabRow));
csv += rowDelim;
csv += formatRows($rows.map(grabRow)) + '"';
// Data URI
var csvData = 'data:application/csv;charset=utf-8,' +
encodeURIComponent(csv);
// For IE (tested 10+)
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(csv))], {
type: "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, filename);
} else {
$(this)
.attr({
'download': filename
,'href': csvData
//,'target' : '_blank' //if you want it to open in a
new window
});
}
//------------------------------------------------------------
// Helper Functions
//------------------------------------------------------------
// Format the output so it has the appropriate delimiters
function formatRows(rows){
return rows.get().join(tmpRowDelim)
.split(tmpRowDelim).join(rowDelim)
.split(tmpColDelim).join(colDelim);
}
// Grab and format a row from the table
function grabRow(i,row){
var $row = $(row);
//for some reason $cols = $row.find('td') || $row.find('th')
won't work...
var $cols = $row.find('td');
if(!$cols.length) $cols = $row.find('th');
return $cols.map(grabCol)
.get().join(tmpColDelim);
}
// Grab and format a column from the table
function grabCol(j,col){
var $col = $(col),
$text = $col.text();
return $text.replace('"', '""'); // escape double quotes
}
}
// This must be a hyperlink
$("#export").click(function (event) {
// var outputFile = 'export'
var outputFile = window.prompt("What do you want to name your
output file (Note: This won't have any effect on Safari)") ||
'export';
outputFile = outputFile.replace('.csv','') + '.csv'
// CSV
exportTableToCSV.apply(this, [$('#dvData > table'),
outputFile]);
// IF CSV, don't do event.preventDefault() or return false
// We actually need this to be a typical hyperlink
});
};
</script>
use this, add ?> before it and <?php after script
<?php
/* your php code */
?>
<script type='text/javascript'>
// your script
</script>
<?php
/* your php code */
?>
Top answer from a previous question
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
works if you define and use the variable in PHP, and want to pass the variable in the Javascript.
If you are running in a PHP file (which you are) you can also use
function foo()
{
var i = 0 ;
i = <?php echo $my_var; ?>
}

Postpone the ads script execution

With the help of the following php function:
<?php
if (!function_exists('wrapAds')) {
function wrapAds($current_banner_name){
$STRING_EMPTY = "";
$openExprResult = array();
$closeExpreResult = array();
$openExpr = "/(<div[^>]*>)/";
$closeExpr = "/(<\/div>)/";
$banner = tsp_get_banner($current_banner_name);
$result = '<pre data-script-reference>'
.htmlspecialchars($banner)
.'</pre>';
return $result;
}
}
?>
I am rendering the following markup:
<pre data-script-reference="1"><!--- s: middle-box-sidebar -->
<div class="ads middle-box-sidebar"><script type="text/javascript">
var FW_type = "4w";
var FW_code = "18xxxx;95xxx;70xxx;0";
var FW_dimension = "300x250";
var FW_category = "gossip";
</script>
<script src="//optimized-by.4wnetwork.com/simply_loader.js?4wvideo=true" type="text/javascript"></script></div>
<!--- e: middle-box-sidebar --></pre>
Now I am tring to postpone the encoded script execution later with the following script:
<script type="text/javascript">
[].slice.call(document.querySelectorAll('pre[data-script-reference]'))
.forEach(function(item){
var txt = document.createElement("textarea");
txt.innerHTML = item.innerHTML;
var parentNode = item.parentNode;
var p0 = txt.innerText;
// parentNode.removeChild(item);
parentNode.innerHTML += p0;
</script>
seems that decoded script isn't executed at all, what I am doing wrong?
After a trillion of useless code executions, I just noted a curious statement inside a long list of warnings:
"Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.". I googled around this message and I found a nice question.
The only not accepted answer suggest postscribe.js
Asynchronously write javascript, even with document.write.
Remote scripts, especially ads, block the page from doing anything
else while they load. They contribute a large % to load times which
affects your bottom line. Asynchronous ads do not block the page and
can be delivered after core content - Async FTW.
Why is it so hard to deliver ads asynchronously? Because they may
contain calls to document.write, which expects to be handled
synchronously. PostScribe lets you deliver a synchronous ad
asynchronously without modifying the ad code.
So, since I have to manage both ads in the body and in the sidebar, I made a little refactoring, moving the php function in the functions.php:
/**
* redefine and get the legacy ads block from base library by name
* render as encoded plain text inside a *pre* wrapper
*/
function tsp_get_banner($current_banner_name){
$STRING_EMPTY = "";
// https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
$openExpr = "/(<div[^>]*>)/";
$closeExpr = "/(<\/div>)/";
$openExprResult = $closeExpreResult = array();
$banner = original_tsp_get_banner($current_banner_name);
preg_match($openExpr, $banner, $openExprResult);
$banner = preg_replace($openExpr, $STRING_EMPTY, $banner);
preg_match($closeExpr, $banner, $closeExpreResult);
$banner = preg_replace($closeExpr, $STRING_EMPTY, $banner);
return wrapAdsSnippet($banner, $openExprResult[0], $closeExpreResult[0]);
}
function wrapAdsSnippet($source, $prefix, $postfix){
$result = '<pre data-script-reference style="display:none;">'
.htmlspecialchars($source)
.'</pre>';
if(isset($prefix) && isset($postfix)){
$result = $prefix.$result.$postfix;
}
return $result;
}
then I changed the inclusion of the block:
so that I don't need to change anything.
<?php
echo tsp_get_banner("middle-box-sidebar");
echo renderAds("middle-box-sidebar");
?>
I have just to change the final script to include in the footer.php:
var MyCompanyLab;
(function (MyCompanyLab) {
"use strict";
var Ads;
(function (Ads) {
var Optimization;
(function (Optimization) {
var PostProcessor = (function () {
function PostProcessor() {
}
PostProcessor.postponeAdsExecution = function () {
$("pre[data-script-reference]").each(function (idx, item) {
var parentNode = item.parentNode;
postscribe(parentNode, $('<textarea />').html(item.innerHTML).text(), {
done: function () { },
error: function () { },
releaseAsync: true,
});
parentNode.removeChild(item);
});
};
return PostProcessor;
}());
Optimization.PostProcessor = PostProcessor;
})(Optimization = Ads.Optimization || (Ads.Optimization = {}));
})(Ads = MyCompanyLab.Ads || (MyCompanyLab.Ads = {}));
})(MyCompanyLab|| (MyCompanyLab= {}));
<script type="text/javascript">
...
MyCompanyLab.Ads.Optimization.PostProcessor.postponeAdsExecution();
...
</script>

How do you use a php variable for directory path?

I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);

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