Suggestion list won't be displayed - php

Let's say it looks like this:
<input type='text' name='customer' onkeyup='searchFor(this.value);' list='customers'>
And I have a datalist (which is embedded in PHP code which will be returned somewhere on the page)
<datalist id='customers'>
<option>$customer[0]['name']</option>
</datalist>
I want to enter a customer id and then it should return the name of the customer as a suggestion list below my text field.
That's my MySQL Query which works (var_dump() returns the correct value if entered a number)
$customer = $database->query("SELECT * FROM customers WHERE customerID LIKE ('%".$_POST["searchterm"]."%')")->fetchAll(PDO::FETCH_ASSOC);
But it doesn't show a suggestion list with my names.
In my opinion it's not working because I enter a number.
edited:
function searchFor(suchbegriff){
var xmlHttp = null;
if (typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
if (!xmlHttp) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = null;
}
}
}
if (xmlHttp) {
var url = "includes/search/search.php";
var params = "suchbegriff="+suchbegriff;
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("ergebnis").innerHTML = xmlHttp.responseText;
}
};
xmlHttp.send(params);
}
}
edited2
search.php
<?php
include_once("../Dbo.class.inc");
if (isset($_POST["searchterm"])){
$customer = $database->query("SELECT * FROM customers WHERE customerID LIKE ('%".$_POST["searchterm"]."%')")->fetchAll(PDO::FETCH_ASSOC);
echo "<datalist id='customers'>";
foreach($customer as $key => $value){
foreach($value as $key2 => $value2){
if($key2 == "Name" || $key2 == "name"){
echo "<option>" . $value2 . "</option>";
}
}
}
echo "</datalist>";
} ?>

Related

how to call name onkey up using ajax?

i am new to ajax. I want to get name from the database according to onkey up but i am getting this error in console "Invalid left-hand side in assignment". and when i type its showing "showname function is not defined".?
This is my code.
Search:
This is myscript
function showname(d) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp= new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "ajax2.php?name"=+d, true);
xhttp.send();
}
this ajax2.php code
$name = $_GET["name"];
$db = new mysqli("localhost", "root", "", "customername");
$conn = $db->query("select customerName from customers like '".$name."%'");
$fetch = $conn->fetch_array();
?>
<?php foreach ($fetch as $key => $value) :?>
<p><?php echo $value ?></p>
<?php endforeach; ?>
Thanks you in advance.
xhttp.open("POST", "ajax2.php?name"=+d, true);
I think you got a typo there, put the = into the quote marks.
xhttp.open("POST", "ajax2.php?name=" + d, true);

Cannot read property 'readyState' of undefined

spend hours to find what has gone wrong, but failed.. since I'm new to Ajax, so I've no idea what I'm seeing. really need you guys to find the bug.
HTML
<!doctype html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Chuff Bucket</h3>
Enter the food you would like to order:
<input type="text" id="userInput">
<div id="underInput" />
</body>
</html>
javascript :
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXobject){
try{
xmlHttp = new ActiveXobject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XmlHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("can't create that object");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = "<span style='color:blue'>" + message + "</span>";
setTimeout('process()', 1000);
}else{
alert('something went wrong');
}
}
}
PHP (I think this file caused the problem)
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray)){
echo 'We do have ' .$food. '!';
}else if($food == ''){
echo 'Enter a food name.';
}else
{
echo "no, we don't sell " .$food. "!";
}
echo '</response>';
?>
JavaScript is case sensitive. You've got some syntax errors due to improper casing on some of the objects you're trying to create:
ActiveXobject
should be
ActiveXObject
^
and
XmlHttpRequest
should be
XMLHttpRequest
^^
The end result is that you're trying to create things that don't exist, resulting in the xmlHttp variable that is always false or undefined.
Your object creation logic seems backward (should try to create the modern object when you can, do the IE thing only if necessary), and mis-capitalized.
Try:
if (window.XMLHttpRequest) {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
} else {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}

xmlDocumentElement is not defined

Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onLoad="process()">
<h3>WELCOME to our online food store</h3>
Please type what you want to order:
<input type="text" id="userinput" ></input>
<div id="underInput"></div>
</body>
</html>
PHP
<?php
header('Content-Type: text/xml');
echo"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','mutton');
if(in_array($food,$foodArray))
echo 'We do have'.' '.$food;
elseif($food=='')
echo 'type something dude!';
else
echo 'Sorry we dont sell'.' '.$food;
echo '</response>';
?>
JS
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else if(window.XMLHttpRequest)
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert('cannot connect to database!');
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
food = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "ajax.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeOut('process()',1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumnetElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHtml = "<span style='color:blue'" + message + "</span>";
setTimeOut('process()',1000);
}
}
else
{
alert('something went wrong');
}
}
Everything seems to be fine to me but I still keep getting the error 'xmlDocumentElement is not defined'. Seems like this is an error due to some parsing issues within javascript and php.. Please help me fix this error. thanks
try to use
window.setTimeOut('process', 1000);

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Fault in Ajax php search

In the following Ajax based search box, if the character is at position 0 then the respective name in the array is not returning but for characters at other positions everything works well. Please fix this...
PHP
$query = $_GET['query'];
$names = array('abc', 'hello', 'cool', 'fun', 'demo', 'test');
foreach($names as $name)
{
$str = strpos($name, $query);
if(!empty($str))
{
echo "$name ";
}
}
HTML
<form name='myForm'>
Name: <input type='text' onblur="ajaxFunction(this.value);" name='username' /> <br />
Time: <input type='text' disabled="disabled" name='time' />
</form>
AJAX
function ajaxFunction(val) {
var ajaxRequest;
try {
//Opera, Safari and Firefox xml object
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
//Internet Explorer xml object
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
//Old browser's xml object
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
} else {
//do nothing
}
}
ajaxRequest.open("GET", "names.php?query="+val, true);
ajaxRequest.send(null);
}
You can use the following -
if($str !== FALSE)
{
echo "$name ";
}
That's maybe of the 0 Value returned by strpos (it returns an integer) ... i mean the "if" statement could value it as a false.
Try to compare like
if(strpos($name, $query) === false){ .... do something..... }

Categories