So I am using this code:
function updateSelect(a) {
$type = a;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest(); }
else {
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","selectbox.php?type=".$type,false);
xmlhttp.send();
selectText=xmlhttp.responseText;
document.getElementById("cultpicklist").options.length=0;
document.getElementById("cultpicklist").innerHTML = selectText;
And for some reason it gives me EVERY option value on the entire page (I have several DISTINCT select boxes)! selectText only pulls from a small subset of the database (i.e. an entirely different table from where this data is coming from) - why would it be doing this?
Here's what is generated on selectbox.php:
<?php
include "mysql_config.php";
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect to the database, please contact administrator');
}
mysql_select_db($db);
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>
Related
I have a web page with a large number of select boxes plus a few other types of inputs. I want to populate these select boxes and input boxes with values held in a MySQL database based on the values selected in two of the select boxes.
I have tried to use AJAX to request the data but cannot see how to return the data held in a database to a specific select box from the server php script.
jscript used to request the data is as follows
<script>
function venueChange(str) {
if (str == "") {
document.getElementById("Venue").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("Player1").innerHTML = this.responseText;
}
};
var opponent_name = document.getElementById("Opponents").value
var variables = "venue_name=str&opponent_name=Hello World";
xmlhttp.open("GET","getTeamPHP?" + variables,true);
xmlhttp.send();
}
}
</script>
The getTeamPHP files is as follows;
<?php
require '../../configure.php';
$q = intval($_GET['venue_name']);
$v = $_GET['opponent_name'];
$database = "matchmanagementdb";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,$database);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,$database);
$sql="SELECT * FROM user WHERE Opponents = '".$q."' AND Venue = '".$v."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo document.getElementById("Player1").innerHTML = $row['FirstName'] ;
}
mysqli_close($con);
?>
I have decided that the solution lies in creating three scripts to;
1) read the search details
2) search the database and populate the form
3) allow updates.
As per http://www.dynamicdrive.com/forums/showthread.php?45895-How-to-populate-php-html-form-with-MySQL-data.
So closing this question.
I'm new to AJAX and I'm trying to create two dropdownlists of options from a database depending on what the user selects in two previous dropdowns. I've checked every way shape and form I've looked up but one dropdownlist doesn't return any values and the other says internal server error 500.
This is where the onChange event is, triggering the AJAX functions:
<select required="true" id="oficinaLoc" name="oficinaLoc" onchange="getAgent(this.value); selClub(this.value)">
<option value="">Seleccione Unidad</option>
<option value="680 - Centro de Tecnología de Información">680 - Centro de Tecnología de Información</option>
<option value="681 - Educación Agrícola">681 - Educación Agrícola</option>
<option value="682 - Planificación y Evaluación">682 - Planificación y Evaluación</option>
<option value="683 - Medios Educativos e Información">683 - Medios Educativos e Información</option>
<option value="684 - Ciencias de la Familia y el Consumidor">684 - Ciencias de la Familia y el Consumidor</option>
etc...
These are my AJAX functions:
function getAgent(str) {
if (str == "") {
document.getElementById("dispAgente").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("dispAgente").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getagent.php?q="+str,true);
xmlhttp.send();
}
}
function selClub(unidad) {
if (unidad == "") {
document.getElementById("dispNombre").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("dispNombre").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnombre.php?j="+unidad,true);
xmlhttp.send();
}
}
And these are the PHP pages it calls to through the XMLHttpRequest respectively:
getagent.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$q = ($_GET['q']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$q."%'";
$result = mysqli_query($con,$sql);
echo '<select name="agenteExt"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
getnombre.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$j = ($_GET['j']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);
echo '<select name="nombreClub"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombreClub'] . ">" . $row['nombreClub'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
The getAgent function doesn't return any options in the dropdownlist even though it creates the empty select. The selClub function gives me a 500 internal server error on the xmlhttp.open("GET","getagent.php?q="+str,true); line. I really don't know what else to do, I've followed every online article I've found about this to the dot.
A 500 error is a server error, so that means the problem will be in PHP and I'm seeing alot of issues there. I'm not sure that this is a complete list,...you'll need to debug it yourself, but here's a couple that aren't helping.
$j = ($_GET['j']);
$j = $_GET['j'];
//dump the ()
echo '<select name="nombreClub"';
echo '<select name="nombreClub">';
//closing > is missing
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
echo "<option value=\"".$row['nombre']."\">".$row['nombre']."</option>";
//quotes around the value are missing
If you view the errors thrown by the PHP files, then you'll be on your way.
Good luck
I am building a simple app with Intel XDK and I need to connect my app to a mysql database. Because the Intel XDK does not allow PHP files I needed to connect my html to php via javascrapt and json.
Here is the PHP code I found and edited which sends an PHP array as JSON object to the Intel XDK app:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT * FROM quotes LIMIT 1";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_row($result)) {
$jsonData = $row;
}
/* free result set */
mysqli_free_result($result);
//encode to JSON format
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
else {
echo "<h1>" . json_encode($jsonData) . "</h1>";
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
My index.html has the following code:
<head>
<script>
function GetQuote() {
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)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://domain/db.php?get_rows=json", false);
xmlhttp.send();
}
</script>
</head>
<body onload="GetQuote()">
<div id="quote"> </div>
</body>
My code is working and my app shows the latest row in my table. The problem is that this code returns the entire row so I get someting like this on my screen:
["column1","column2"]. What I need is "Column1" as a record and "column2" as a record.
Anyone who can help me? I've been working on this problem the entire day and can't find a solution.. Thanks!
This is the code I have now:
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxx", "xxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
I now just get an empty screen with [null,null].. Anyone knows what's wrong with this code? I tried debugging, but I am new to PHP and I can't manage to make it work.. Thanks!
Try something like this
$query = "SELECT column1,column2 FROM quotes LIMIT 1";
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret['name1'] = $row['column1'];
$ret['name2'] = $row['column2'];
// Or you can simply use, comment the above two lines and uncomment the following two lines.
//$ret[] = $row['column1'];
//$ret[] = $row['column2'];
//encode to JSON format
echo json_encode($ret);
If you find any type error here, kindly share
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 ©</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?
i am trying to change the select query on click or on change of the button,
the table name field names in the table general are equal to the fragment after page = (About, ContactInformation)
i'm not getting any error nor getting any result
index page code
<script>
function selectQuery(str) {
if (str == "") {
document.getElementById("editor").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("editor").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","queries.php?page="+str,true);
xmlhttp.send();
}
}
</script>
<ul>
<li><i class="fa fa-file-text"></i> About us</li>
<li><i class="fa fa-list-alt"></i> Contact us</li>
</ul>
queries.php page
<?php
$page = intval($_GET['page']);
$result = mysql_query("SELECT general.'".$page."' ".
"FROM general") or trigger_error(mysql_error());
echo $result;
?>
i tried to echo $page in the queries.php file directly but also it is not showing, seems its not even getting here,
so can anyone help pls
You aren't fetching those results. You need to use mysql_fetch_* functions to get those rows. Now the next part is whether you would like to get a JSON response or just output an HTML markup that can be used directly.
Here's what the fetching would look like:
<?php
$page = $_GET['page'];
$data = array();
$result = mysql_query("SELECT general.".$page." FROM general") or trigger_error(mysql_error());
while($row = mysql_fetch_assoc($result)) {
// fetch the results
$data[] = $row;
}
echo json_encode($data);
?>
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Here's a version with mysqli:
<?php
$default_columns = array('About', 'ContactInformation', 'Others', 'Home');
if(isset($_GET['page']) && in_array($_GET['page'], $default_columns)) {
$return_value = array();
$page = $_GET['page'];
$db = new mysqli('localhost', 'username', 'password', 'database');
$sql = "SELECT $page FROM general";
$query = $db->query($sql);
while($row = $query_fetch_assoc()) {
$return_value[] = $row[$page];
}
echo implode(' ', $return_value);
}
?>