php/sql/html: Data dont show in the option field - javascript

I'm sorry if this question may sound stupid, but i have one problem with my code that i don't know how solve even though i think it really easy for other people.
I'm making some form when user enter their info (example: username) then the output will shown in the option field (example:responsibility). For your information every username have many responsibility.
The problem is the output is creating many option field and not only one.
below is my php code that related with option field:
<?php
// 3.php is my config file
require("3.php");
$link = mysqli_connect($h,$u,$p,$db);
//if ($link)
//echo "Connection OK";
//else echo "connection failed";
$q = $_GET['q'];
$query="SELECT resp_name FROM view_ss_user_responsibility WHERE user_name ='".$q."'";
$result = mysqli_query($link,$query)
or die("Error: ".mysqli_error($link));
while ($row = mysqli_fetch_array($result)){
$fn=$row[0];
echo "<br>";
//echo "<td>$row[0]</td>";
echo "<tr><td>Responsibility:</td>
<td align=center><form><select><option value='$row[0]'>$fn</option></select></form></td></tr>";
}
echo "</table>";
?>
And also this is the output (i'm using ajax, so no submit button)
if you want to see my html/javascript file:
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("search").innerHTML="";
document.getElementById("search").style.border="0px";
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 (this.readyState==4 && this.status==200) {
document.getElementById("search").innerHTML=this.responseText;
document.getElementById("search").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
username <input type="text" size="30" name ='pass' onkeyup="showResult(this.value)"><br>
<div id="search"></div>
</form>
</body>
</html>
so, base from this i hope someone can tell me on how to do it, thank you.
(why is this getting downvote?.its not like i'm forcing you all to answer it)

Hope it will work fine..
Change this to:
while ($row = mysqli_fetch_array($result))
{
$fn = $row[0];
echo "<br>";
//echo "<td>$row[0]</td>";
echo "<tr><td>Responsibility:</td>
<td align=center><form><select><option value='$row[0]'>$fn</option></select></form></td></tr>";
}
echo "</table>";
This:
echo "<table><tr><td>Responsibility:</td><td><select>";
while ($row = mysqli_fetch_array($result))
{
$fn = $row[0];
echo "<option value='$row[0]'>$fn</option>";
}
echo "</select></td></tr></table>";

Related

Can't get ajax working with PHP to load a table of info from MySQL

So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright &copy</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?

Passing a string variable through ajax

The variable is passed through ajax and it is a database name. When the link is clicked it's supposed to retrieve a data from the the database. the link and the variable is on the same page. Here is the code for the link:
$x = strval($_GET['x']);
echo ''.$seatid.'';
The $x variable contains the table name of the database. And here is the code for ajax:
function showInformation(str)
{
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("txtInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?x="+str,true);
xmlhttp.send();
}
Here is the getinfo.php:
<?php
session_start();
$_SESSION['login']="1";
$x = strval($_GET['x']);
$con = mysql_connect('localhost','root','Newpass123#','seatmapping');
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('seatmapping');
$sql="SELECT name, seatid FROM $x WHERE seatid = 1";
$result = mysql_query($sql) or die("Query Error " . mysql_error());
...
...
?>
I can't get it to work when i click the link it does not display the data from the table.
Please help me. Any kind of help is appreciated. Thanks in advance..
Can you please try this:
Replace the line
echo ''.$seatid.'';
With the below:
echo ''.$seatid.'';
This will solve your problem.
You are not passing the ID of the expected element.
echo ''.$seatid.'';
Replace this line, instead
echo ''.$seatid.'';

PHP and Ajax using onchange event

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>

uncaughtSyntaxError/unexpected number error when i attempt to copy a php variable into a javascript variable

I have a program where in need to get todays date in php and then copy that variable to a javascript variable. When i do i get an error uncaughtSyntaxError/unexpected number. I use the date() function that should already store the date time as a string, i don't quite understand the reason for this error, any help is appreciated...my code is below:
<!DOCTYPE html>
<html>
<head>
<script>
var tmr;// timer
var incidentReloader;
function UpdateTable()
{
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 && xmlhttp.status==200)
{
var tokens = xmlhttp.responseText.split("|");
alert(tokens[0]+", "+tokens[1]);
}
}
xmlhttp.open("GET","update_ajax_test.php?date1="+newDate,true);
xmlhttp.send();
}
</script>
</head>
<body onload="tmr=setInterval(UpdateTable,5000)">
<?php
mysql_connect("xxxxxxxxxxxxxx", "xxxxxxxxxxxxxx", "xxxxxxxxxxxxxx") or die("not logged in");
//////now selecting our database
mysql_select_db("xxxxxxxxxxxxxx") or die(mysql_error());
$res = mysql_query("SELECT num FROM ajax_table");
$numEnter=$_GET['name'];
echo $numEnter;
echo'<form method="get" action="ajax_test.php">';
echo' <input type="text" name="name"><br>';
echo' <input type="submit" name="submit" value="Submit Form"><br>';
echo'</form>';
date_default_timezone_set('America/New_York');
$date is variable that i will have to copy into php
$date = date('Y-m-d H:i:s');
echo $date;
mysql_query("INSERT INTO ajax_table(num,last_updated) VALUES ('$numEnter','$date')");
echo"<table border=1 id='t1'>";
while ($row = mysql_fetch_array($res))
{
echo"<tr><td>";
echo $row['num'];
echo"</td></tr>";
}
echo"</table>";
?>
<script type="text/javascript">
here is where i get the error
var newDate=<? echo $date; ?>;
</script>
</body>
</html>
use
var newDate = "<?php echo $date ?>";
var newDate=<? echo json_encode($date); ?>;

PHP & AJAX & MySQL integration

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

Categories