Fault in Ajax php search - php

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..... }

Related

Suggestion list won't be displayed

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>";
} ?>

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.

ajax json decode mysql fetch array

$result = mysql_query ("SELECT * FROM order_list");
$test = array();
$i=0;
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
and a AJAX javascript
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 is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("resultTXT").value = eval(" (" + ajaxRequest.responseText + ")");
}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}​
the javascript function wont store the array into the textbox
can anyone tell me whats the problem here?
Thanks
try:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo json_encode($myjsons);
instead of
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
you can use jquery library for tha ajax call http://api.jquery.com/jQuery.post/
$.post('userfind.php', function(data) {
$("#resultTXT").val(data);// ==document.getElementById("resultTXT").value =data;
},'json'
);
JSON output would be invalid in your example, build the array and out put a single json encoded array like so:
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo json_encode($myjsons);

Problem in php ajax post value

I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.

Categories