I want to make a autocomplete to my input field.
All the data is fetched from my database and handled with my autocomplete.php file - its works fine and is storing all the matching columns in a XML file which is sent back to the server.
Onkeyup i GET send with q= "the typed string" to the autocomplete.
Im having trouble handling the XML file when its received from the server. My plan is to append all the matching results to my datalist, which will work as a autocomplete?
Here is my code:
<input id="showCustomerId" name="customer" type="text" min="1" max="100" list="customerlist" required>
<datalist id="customerlist"></datalist>
script:
$("#showCustomerId").on('keyup', function(){
var str = document.getElementById('showCustomerId').value;
var xmlhttp;
if (str.length===0) {
document.getElementById("customerlist").innerHTML="";
return;
}
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) {
var docroot= xmlhttp.responseXML.documentElement;
var customers = docroot.getElementsByTagName('customer');
for(var i=0; i<customers.length; i=i++){
var option = customers[i].firstChild.nodeValue;
$("#customerlist").append("<option value=\"" +option+ "\">");
}
}
}
xmlhttp.open("GET","ini/search-customers.php?q="+str,true);
xmlhttp.send();
});
autocomplete.php
$q=$_GET['q'];
$result = // do query;
$xml = new SimpleXMLElement('<xml/>');
while($row = mysqli_fetch_assoc($result)){
$xml->addChild("customer",$row['customer_id']);
}
header('Content-type:text/xml');
print($xml->asXML());
Right now my problem is not getting the value, when i alert the result in xml handler function i get the right values, but when i do the code like i have here, my website freezes!
I got the values, but i just cant append them to my datalist the right way?
I guess Easiest way to build autocomplete is by jQuery Autocomplete or Twitter Typehead. So simple jquery is better suited for this situation. Add jQuery Latest version in head
Code is not tested.
$(document).ready(function(){
//Assuming #customerlist is the ID of the text box which you need to see autocomplete
//No need to get value also - by default
$("#customerlist").autoComplete({source:"ini/search-customers.php"});
// Same time autocomplete send term as default GET variable
});
At serverside - search-customers.php
$q=$_GET['term'];
$result = // do query;
$json = new Array();
while($row = mysqli_fetch_assoc($result)){
$json[] = $row['customer_id'];
}
header('Content-type:application/json');
echo json_encode($json);
Related
I'm sending a variable from a form using AJAX and this variable is proccess and sends to a PHP file that makes a MySQL query. The value of the input text is setting when I click in a row of one table. When I click the button to send the variable it returns the result of the mysql query. Well, if I click one more time in the button when the value of the input is other the query isn't modify, it returns me the first query. I need to refresh that query and I think that it's possible if I clear the variable.
I put here the code of all. Thanks.
HTML Code
<td><input type="hidden" id="prueba" name="prueba"/></td>
<script type="text/javascript">
var valor=document.getElementById("prueba").value;
</script>
<td><input type="button" name="ver" onclick="load(valor)" value="Ver linea seleccionada"/></td>
AJAX code
function load(str)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mus").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","mostralle.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+str);
}
PHP Code (mostralle.php)
include"conexion.php";
$q=$_POST['q'];
mysql_connect($servidor, $usuario, $clave)or die (mysql_errno().mysql_error());
mysql_select_db($basedatos)or die (mysql_errno().mysql_error());
$result=mysql_query("SELECT Serie, Numeroas, Numlinea, Codart, Cant, Descripcion, Precio, Tipoiva, Subtotal FROM PRESUP_D WHERE Serie='$q' OR Numeroas='$q'");
while($row=mysql_fetch_row($result)){
echo "<tr>";
for($i=0;$i<mysql_num_fields($result);$i++){
echo "<td>$row[$i]</td>";
}
echo "</tr>";
}
mysql_close();
I have the following Code in cat.php file:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsub.php?q="+str,true);
xmlhttp.send();
}
</script>
<select name="users" onchange="showUser(this.value)">
<option value=""></option>
<?php
$query = "SELECT cat from category GROUP BY cat";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num=mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row=mysql_fetch_assoc($result);
echo "<option value=''>".$row['cat']."</option>";
}
echo "</select>";
<div id="txtHint"></div>
And after Calling the function - getsub.php
<?php
require_once('connect_db.php');
//get the q parameter from URL
$q=$_GET["q"];
$query = "SELECT sub from category WHERE cat = '".$q."'";
$result = mysql_query($query);
if(!$result){
mysqli_error();
}
while ($row = mysql_fetch_assoc($result)){
?>
<select name="sub">
<?php
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
echo "<option value='".$row['sub']."'>".$row['sub']."</option>";
}
?>
<select>
<?php
}
I'm looking forward to have a relation between Main Category and Sub Category. I want to Select the Main category and then calling the javascript function in order to show another select input for the Sub Category . The above code outputs nothing and I can't seem to find why?
Please Help
Your code looks fine but you have just a php tag in the end of the while loop that needs to be closed.
Code looks fine. Try using the firebug extension for Firefox.
Open net panel in firebug and then see what data are you sending and what response in actually generating.
This will definitely help.
Also in cat.php, instead of using plain AJAX, try using jQuery as this will reduce large line of code as
// Just incude jQuery beforehand
script>
function showUser(str)
{
$.get("getsub.php",{q:str},function(data){
$("#txtHint).html(data);
});
}
</script>
I have AJAX code here that pass multiple values to PHP. But the problem is that the PHP can't get the value pass by AJAX and nothing is added on the database. However in my submit button I have an onclick event that calls addAnnouncement() and I think it is working because I put an alert in my ajax code and everytime I click that button it says OK.
So I think the part of the problem is in the passing of the variables.
What do you think is the problem in my code?
AJAX CODE:
function addAnnouncement()
{
var subject = document.getElementById("subject").value;
var name = document.getElementById("name").value;
var announcement = document.getElementById("announcement").value;
var xmlhttp;
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)
{
if(xmlhttp.status==200){
alert("OK");
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
var variables = "subject=SAMPLE&name=HARVEY&announcement=HELLO";
xmlhttp.open("POST", "addAnnouncement.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(variables);
return false;
}
This is the PHP code that gets the values pass by AJAX.
PHP CODE:
<?php
require_once("config.php");
$subject = $_POST['subject'];
$name = $_POST['name'];
$text = $_POST['announcement'];
$dateTimeNow = date("Y-m-d H:i:s");
$query = "INSERT INTO table_announcement(subject, name, text, dateTimePosted)".
"VALUES('$subject', '$name' , '$text', '$dateTimeNow')";
$data = mysql_query($query)or die(mysql_error());
if($data){
echo "ADDED!";
}
else{
echo "ERROR!";
}
?>
Just return false when exiting from the event handler to prevent the default behaviour of the submit button (i.e. submit the form):
function addAnnouncement() {
// …
return false;
}
Also check the status of your XMLHttpRequest when it reaches readyState 4 (it might be something different then 200) and properly encode query string parameters with encodeURIComponent. Last, but not least, your code is open to SQL injection. Fix that by using prepared statements (available in MySQLi and PDO. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial).
I'm building a PHP script that sends an email to people on their birthdays. I also need a small web interface where I can turn the entire program on or off, watch who is celebrating his birthday today and see if any mails could not be send. The php on the server is working, but I'm struggling with the html and javascript interface. Specifically the Ajax request that gets the information from the server. it works fine in firefox, chrome and opera, but in Internet Explorer 8 I don't get a response from the server. The readyState switches to 4, but the status remains 0 and the responseText is empty.
After googling I found out that a lot of people advice JQuery, but I couldn't get that to work in any browser. I want to find out more about it, because it seemed pretty easy, but for now I would like to know how to do this without JQuery.
edit
In response to questions from the comments, switching the if and else statements yields the same results. As does changing the connection from 'open' to 'close', incidentally, it is supposed to be close, I can't remember why I changed it, probably just trying something out of frustration. Finally I added the server side php code. The server sends back string data in case 'action' is switchonoff or, just a header with no text if action is clearlog and a jsonarray if action is initialize. Whatever the request the server's HTTP status is always 0.
<script type="text/javascript">
function loadXMLDoc(action) {
var parameters = "action="+encodeURI(action);
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",'http://mailer.test/App/postscript.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "open");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
if(action == 'switchonoff'){
document.getElementById("onoffbutton").innerHTML=xmlhttp.responseText;
} else if(action == 'initialize'){
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("onoffbutton").innerHTML=response['onoff'];
document.getElementById("birthdays").innerHTML=response['birthdays'];
document.getElementById("errors").innerHTML=response['errors'];
} else if(action == 'clearlog'){
document.getElementById("errors").innerHTML="";
}
}
}
}
window.onload = function() {
loadXMLDoc('initialize');
}
</script>
edit, here's the php script
<?php
include "settingschanger.php";
include "customercsv.php";
if (!isset($_POST['action'])) {
$_POST['action'] = 'dummy';
}
$post = $_POST['action'];
if(strcmp($post, "initialize") == 0) {
$settings = new SettingsChanger();
$onoff = $settings->getOnOff();
$csv = new CustomerCSV();
$csv->openFile((__DIR__).CustomerCSV::FILENAME);
$todaysbirthdays = $csv->getTodaysBirthdays();
$birthdays = "";
foreach ($todaysbirthdays as $row) {
$birthday = "";
foreach ($row as $data) {
$birthday .= $data . " ";
}
$birthdays .= $birthday . "<br />";
}
$errorLogArray = $settings->getErrorLog();
$errors = "";
foreach($errorLogArray as $line) {
$errors .= $line . "<br />";
}
$result = json_encode(array('onoff'=>$onoff, 'birthdays'=>$birthdays, 'errors'=>$errors));
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "switchonoff") == 0) {
$settings = new SettingsChanger();
$result = $settings->changeOnOff();
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "clearlog") == 0) {
$settings = new SettingsChanger();
$settings->clearLog();
header("HTTP/1.1 200 OK");
}
?>
Try with xmlhttp.send(parameters); after xmlhttp.onreadystatechange statement.
I had some issues with the returned content being empty in older versions of IE ( less than v9), but the success-function was triggered.
Then I found out that I was using HTML5 tags, and in IE, for some odd reason, HTML5 output via an AJAX-request doesn't work and returns an empty or no DOM.
Look at the last edit in "jquery .load() not inserting data in ie8 and below".
Well, I got the site to work. Instead of a post request I now use a get request and that seems to work. It's not perfect and I'll continue looking for a way to do it with a post request, but for now it'll work.
I'm trying to get the code below working so that it will call a JS function to pass a value to my PHP file which will return a number of values from a MySQL database. This is part of an assignment I thought would be quite straightforward but I think my problem is with the JavaScript event handler - how to reference the input value maybe?
The HTML:
<form>
<input type="text" name="users" onkeydown="showUser(this)"/>
</form>
<div id="txtHint">
<p id="responder"><b>Person info will be listed here.</b></p>
</div>
The showUser() function:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("responder").innerHTML="";
return;
}
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("responder").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/student_query.php?q="+str,true);
xmlhttp.send();
}
</script>
The PHP:
<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3
$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);
// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>
Like I said, i think my problem is in the event handler, I'm not great with JS. I'd appreciate any help.
Looks like you're sending the input element to your function, not it's value. Try
<input type="text" name="users" onkeydown="showUser(this.value);" />
Also, you should protect your database query from protection by changing your PHP to
$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
echo "";
exit;
}