I am trying to do a connection with the database using AJAX. I am totally new to AJAX...just saw a couple of tutorials and took a code snippet and tried to adapt it to my code.. but when ever I press the button I get the following error Error: Unable to get property 'documentElement' of undefined or null reference
php file
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$title = $_GET['title'];
$conn=("localhost","root","","askthedoctor");
$sql="select patient_text, doctor_text where title='".$title."')";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo $row[0];
echo $row[1];
echo '</response>';
?>
javasscript
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("Cant create that object !")
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
title= encodeURIComponent(document.getElementById("title").value);
xmlHttp.open("GET", "displaypatientmessage.php?title="+title,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
////////////////////////////////error////////////////////
xmlDocumentElement = xmlResponse.documentElement;
/////////////////////////////error/////////////////////////
message1 = xmlDocumentElement.firstChild.data;
document.getElementById("question").innerHTML = message1;
message2 = xmlDocumentElement.firstChild.data;
document.getElementById("answer").innerHTML = message2;
setTimeout('process()', 1000);
}else{
alert('Someting went wrong !');
}
}
}
the form containing the button which calls the javascript
<table id="table" class="table">
<tr>
<th>Messages</th>
<th>Problem Description</th>
<th>Doctor's Answer</th>
<th></th>
</tr>
<tr>
<th><select id="title">
<?php
$sql="select title from messages where paitient_id=(select id from login where username='".$username."');";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result))
{
?>
<?php echo "<option value=\"mesazhi1\">".$row[0]."</option>";}?>
</select>
</th>
<td><textarea rows="17.95" col="100" id ="question" > </textarea></td>
<td><textarea rows="17.95" col="100" id ="answer" readonly> </textarea></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td><input type="button" name="openmessage" value="Display Selected Message" onClick="process()"></td>
</tr>
</table>
</form>
1] One more thing, see the
<?php echo "<option value=\"mesazhi1\">".$row[0]."</option>";}?>
as value of each <option> is same. You will get same value of title at
title= encodeURIComponent(document.getElementById("title").value);
so no matter what option you select, you will always get same value i.e. \mesazhi\.
2] Also, take a look,
$sql="select patient_text, doctor_text where title='".$title."')";
you have not mention the table name.
3] Also why is ) at the end of query?
4] And finally
$conn=("localhost","root","","askthedoctor");
should be
$conn=mysqli_connect("localhost","root","","askthedoctor");
Related
I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**
Ive been try to make a page with Pagination on table. Upon button click, the table in main.php got populated by the first 16 rows retrieved from the query in page.php. For example the retrieved rows were 20. So there would be an excess of 4 for the second page. The thing is when I clicked the "Next" button to show the missing 4 records, the page is then diverted to page.php with the missing records. What I want to happen is for the 20 records in main.php be replaced by the 4 records.
MAIN.PHP
<div id="section">
<head3>Asset Assignment</head3><br><br>
<table>
<td>
<tr>Search Asset:</tr>
<tr><input type="text" id="sidt" name="sid"></tr>
<tr><input type="button" name="searchSub" value="Search" onClick="searchItem()"></tr>
</td>
</table><br>
<table>
<tr>
<td>Employee ID</td>
<td>Asset Serial Number</td>
</tr>
<tr>
<td><input type="text" name="empID"></td>
<td><input type="text" name="srlID"></td>
</tr>
<tr>
<td align="right"><input type="button" name="assign" value="Assign" onClick="assignItem()"></td>
</tr>
</table><br>
</div>
<div id="section2"></div>
JAVASCRIPT
function searchItem()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "asid=" + document.getElementById("sidt").value;
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data()
{
if (xhr.readyState == 4)
{
if (xhr.status == 200)
{
document.getElementById("section2").innerHTML = xhr.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
}
function assignItem(){}
PAGE.PHP
<?PHP
session_start();
$dbHost = "localhost";
$dbUser = "root";
$dbPass = "password";
$dbDatabase = "awsims";
$db = new PDO("mysql:dbname=$dbDatabase;host=$dbHost;port=3306", $dbUser, $dbPass);
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
$startrow = 0;
} else {
$startrow = (int)$_GET['startrow'];
}
$sql = $db->prepare("SELECT * FROM assets LIMIT $startrow, 16");
$sql->execute();
$fetch = $sql->rowCount();
$num=$fetch;
if($num>0)
{
echo "<table style='width: 100%' border='1'>";
echo "<tr><td>ID</td><td>Drug</td><td>quantity</td></tr>";
for($i=0;$i<$num;$i++)
{
$row = $sql->fetch(PDO::FETCH_ASSOC);
$a = $row['SerialNumber'];
$b = $row['AssetType'];
$c = $row['AssetSubType'];
echo "<tr>";
echo "<td>$a</td>";
echo "<td>$b</td>";
echo "<td>$c</td>";
echo "</tr>";
}
echo "</table>";
}
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+16).'>Next</a>';
$prev = $startrow - 16;
//if ($prev >= 0)
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';
?>
Try changing your sql statement to as following query.
$sql = $db->prepare("SELECT * FROM assets LIMIT 16 OFFSET $startrow");
The next and previous link code should be like following.
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.($startrow+1).'>Next</a>';
$prev = $startrow - 1;
echo '<a href='.$_SERVER['PHP_SELF'].'?startrow='.$prev.'>Previous</a>';
Here is the easiest and smartest PHP MySQL Pagination example I had ever read! Very well explained and a full code is provided which is tested and working 100%.
I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment
Below are my code parts javascript, main.php and getparty.php
1) getparty.php code is as follow called from javascript to take details
from party table on change of dropdown value of party from main.php
<?php
$q = intval($_GET['q']);
include "dbc.php";
$sql= mysql_query("Select a.pcode,a.pname,a.discperc,a.delvterm from PARTY a where a.pcode='$q'") or die(mysql_error());
$row = mysql_fetch_array($sql) or die(mysql_error());
$pcode=$row['pcode'];
$ppname=$row['pname'];
$pdiscperc=$row['discperc'];
?>
main.php ... it is my main form to display main form for user to enter
<tr>
<td><font face="verdana" size="2" color="#000000">Party</font></td>
<td>
<?php
<td align="left" >
<?php
$sql="UPDATE PARTY set repo_flag=0 ";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
if ($ppname!="")
{
$sql="UPDATE PARTY set repo_flag=1 where pname='$ppname' ";
}
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
$dropdown = "<select id='pname' name='pname' style='width:275px' onchange='showparty(this.value)' value='<?php echo $ppname; ?>' >";
$query1 = "select pcode,pname from PARTY order by repo_flag DESC ";
$get=mysql_query($query1);
while($row = mysql_fetch_array($get))
{
$dropdown .= "\r\n<option value='{$row['pcode']}'>{$row['pname']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
?>
</td>
</tr>
<tr>
<td><input type="text" maxlength="3" size="3" name="txtdiscperc" value="<?php echo $pdiscperc; ?>"/></td>
</tr>
Javascript .. This is called to take value of party when dropdown
combo changes
<script>
function showparty(str) {
if (str == "") {
document.getElementById("txtpartyname").innerHTML = "";
return;
} else {
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("txtpartyname").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getparty.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I am not getting value of Discount % in main.php, and some other fields also I want to get from party table which I can write code when above discount % gets properly. How can I
Hoping someone can help. I have dynamic drop-downs that have been working great until I added a new item with a space in it. It's confusing me because my second drop-down has items with spaces and the query runs fine with those but the first drop-down fails. I've tried to find any differences that would cause one to fail but I just can't see it. It's been a mixture of scripts that I found and I'm really new to Javascript and PHP so I'm lost. I hope someone can point me to my error. Here's the code I think you need to see The first script is the one that controls the dropdown that is failing the second one is working:
<script type="text/javascript">
function AjaxFunction()
{
var ddstring = document.getElementById("name");
var ddindex = ddstring.options[ddstring.selectedIndex].value;
if (ddindex != 0){
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.type.options.length-1;j>=0;j--)
{
document.searchform.type.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.type.options.add(optn);
}
{
var optn2 = document.createElement("OPTION");
optn2.text = "Select Type";
optn2.value = '%';
document.searchform.type.options.add(optn2,0);
}
{
document.searchform.type.disabled=false;
document.searchform.type.selectedIndex = 0;
var defaultdd = "<?php echo $_SESSION['type'] ?>";
if (defaultdd != ""){
document.getElementById('s2').value = defaultdd;
if (defaultdd != "%"){
AjaxFunction2();
}
}
}
}
}
var url="dd.php";
var cat_id=document.getElementById('name').value;
url=url+"?cat_id="+cat_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
else {
document.searchform.type.selectedIndex = 0;
document.searchform.subcat.selectedIndex = 0;
document.searchform.type.disabled=true;
document.searchform.subcat.disabled=true;
}
}
</script>
<script type="text/javascript">
function AjaxFunction2()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
//alert(httpxml.responseText);
var myarray = JSON.parse(httpxml.responseText);
var myarray=myarray.split(",");
for(j=document.searchform.subcat.options.length-1;j>=0;j--)
{
document.searchform.subcat.remove(j);
}
for (i=0;i<myarray.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.searchform.subcat.options.add(optn);
}
{
var optn2 = document.createElement("OPTION");
optn2.text = "Select Series";
optn2.value = '%';
document.searchform.subcat.options.add(optn2,0);
}
{
document.searchform.subcat.disabled=false;
document.searchform.subcat.selectedIndex = 0;
var defaultdd = "<?php echo $_SESSION['subcat'] ?>";
if (defaultdd != ""){
document.getElementById('s3').value = defaultdd;
}
}
}
}
var url="dd2.php";
var cat_id=document.getElementById('name').value;
var cat_id2=document.getElementById('s2').value;
url=url+"?cat_id="+cat_id;
url=url+"&cat_id2="+cat_id2;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
The Form Elements:
<form name="searchform" method='POST' action='?'>
<table width="534" border="1" cellspacing="10" ID="tdspace">
<tr>
<td>Manufacturer: </td>
<td><select name=name id='name' onchange=AjaxFunction();>
<option value='%'>Select One</option>
<?Php
try {
$dbo = new PDO('mysql:host=localhost;dbname='. $dbname, $username, $password);
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$sql="SELECT Distinct Manufacturer FROM `tbl_Printers` order by `Manufacturer` asc ";
foreach ($dbo->query($sql) as $row) {
if ($row[Manufacturer] == $_SESSION['name'])
$selected = "selected=\"selected\"";
else
$selected = "";
echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";
if( $_SESSION['type'])
{ echo '<script type="text/javascript">AjaxFunction()</script>';
}
}
?>
<?php
if ( $_SESSION['name'] == ""){ $namevalue = 'None Selected';}
else {$namevalue = $_SESSION['name'];}
if ( $_SESSION['type'] == "%"){ $typevalue = 'None Selected';}
else {$typevalue = $_SESSION['type'];}
if ( $_SESSION['subcat'] == "%"){ $subvalue = 'None Selected';}
else {$subvalue = $_SESSION['subcat'];}
?>
</select></td>
<td>Manufacturer:<span style="color:cyan"> <?php echo $namevalue;?></span></td>
</tr>
<tr>
<td>Product Type: </td>
<td><select name=type id='s2' onchange=AjaxFunction2(); disabled=true>
<option value='%' selected>Select Type</option>
</select></td>
<td>Product Type:<span style="color:magenta"> <?php echo $typevalue?></span></td>
</tr>
<tr>
<td>Printer Catagory:</td>
<td><select name=subcat id='s3' disabled=true>
<option value='%' selected>Select Series</option>
</select></td>
<td>Printer Series:<span style="color:yellow"> <?php echo $subvalue;?></span></td>
</tr>
<tr>
<td height="27" colspan="2" ID="centered" style="padding-left:90px"><br /> <input type=submit onclick="s3.disabled=false; s2.disabled=false" class="quick-search-button btn"/></td>
<td>Records Found:<span style="color:black; text-shadow: 0 1px 0 rgba(0, 0, 0, 0.4)"> <?php echo $_SESSION['totalrecords'];?></span></td>
</tr>
<tr>
<td height="28" colspan="3" style="text-align:center"><br />
*Manufacturer is Manditory, all other fields optional. </td>
</tr>
</table>
<br />
<br />
<p><div id="finish">
</p></div>
</form>
This is the php page that is supposed to return the results for the first drop-down although the second drop-down form is practically identical and works:
<?Php
#$cat_id=$_GET['cat_id'];
//$cat_id=2;
$dbhost_name = "localhost";
$database = "database";// database name
$username = "username"; // user name
$password = "password"; // password
//////// Do not Edit below /////////
try {
$dbo = new PDO('mysql:host=localhost;dbname='.$database, $username, $password);
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$str='';
$sql="SELECT Distinct Type FROM `tbl_Printers` where Manufacturer='$cat_id' order by Type asc";
foreach ($dbo->query($sql) as $row) {
$str=$str . "$row[Type]".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
//$main = array($str);
echo json_encode($str);
//echo $str;
?>
I appreciate any help, I've tried searching and normally I don't ask for help but this one is just to far beyond my understanding.
For the moment I have replaced all of my queires to read like this (There are a lot of them considering the paging...) I don't see this as an answer though just a work around.
"SELECT Distinct Type FROM `tbl_Printers` where Manufacturer Like CONCAT('%', '$cat_id', '%') order by Type asc"
The thanks go to Vigour for pointing me in the correct direction. Unfortunately I can't select a comment as the answer or post an answer for my own question until tomorrow because of my reputation, but thank you so much for finding the issue.
The line of code causing the issue was:
echo "<option value=$row[Manufacturer] $selected>$row[Manufacturer]</option>";
It needed to be changed to this to add the quotes as needed and still select the proper saved item:
echo "<option value='" . $row['Manufacturer']."' ".$selected." >" . $row['Manufacturer'] . "</option>";
Better test it, but I think the JS should replace the empty string with + sign in order to pass it correctly:
Replace:
var cat_id=document.getElementById('name').value;
With:
var cat_id=document.getElementById('name').value.replace('/ /gi','+');
You should add the option values with quotation marks, otherwise the spaced values will not be passed.
<option value="Kyocera Mita" >Kyocera Mita</option>