retrieve sql data & print it into form field - php

here is an example that if i enter id then it will retrieve data from database & print it within form fields. my database has only three column- id, name & number. here is my index.html file:
<html>
<head>
<script>
function showData(str)
{
if (str=="")
{
document.getElementById("ajax-content").innerHTML="";
return;
}
// Code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// Code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ajax-content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showData.php?id="+str,true);
xmlhttp.send();
}
return true;
</script>
</head>
<body>
<p>Please Enter Your Staff ID:</p>
<div><input onkeyup="if (event.keyCode == 13) showData(this.value); return false;" /></div>
<div id="ajax-content"></div>
</body>
</html>
and here is my showData.php file:
<?php
// Receive variable from URI
$id=$_GET["id"];
// Connect to your database
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db("test_01", $con);
// Select all fields from your table
$sql="SELECT * FROM staffdetails WHERE id = '".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "Staff Name:" . "<input type='text' value='" . $row['name'] . "'>";
echo "</br>";
echo "Contact No.:" . "<input type='text' value='" . $row['number'] . "'>";
}
// Close the connection
mysql_close($con);
?>
now what i'm trying to do is, display the data in a given form field rather than print data with the form field. that means, the name & number input field will be already in the form with the id field. when i'll enter id then it will pull back the data & display it in the given form field. anyone can help please? thanks!

There's a javascript error in your index.html page. The return true statment should be inside function brackets.
Also try adding document type and content type on top of index.html page to show text fields instead of printing it.
Hope this will help solving your problem.

Related

Run SQL query and update form on drop-down selection

So I have two drop-down lists Category and Sub-category. Sub-category has to be populated by an SQL query once a Category is selected.
I know how to populate from an SQL query:
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table";
$result = mysql_query($sql);
echo "<select name='col'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
But I don't know how to run the query and update list in jQuery:
function updateList(){
//QUERY&fill based on selection//
.val($('select[name="category"] option:selected').val());
}
I spent an hour or so on google and couldn't manage to solve this.
you have to create onchange function in selecting main category and pass it to either jquery or javascript ajax request response to get value from another file having subcategory output with sql where condition as main category value.
echo "<select name='col' onchange='loadXMLDoc()'>";
the above of main cat drop down and its ajax javascript reqest response whould be as below
<script>
function loadXMLDoc()
var maincat=document.getElementByName("col").val();
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("maincat_var=maincat");
}
Create a div with id as myDiv in your main page.
and the other page should have
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table where main_cat=$_POST['maincat_var']";
$result = mysql_query($sql);
echo "<select name='col2'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
You can try using jquery and ajax to load values of subcategory .
Try modifying and using the below code. This code may guide you..
$(document).ready(function(){
$('#submit').click(function() {
$.ajax(
{
url:"subcat.php?id='something'", // Here you can write php variableto pass to next page
success:function(result){
$("#div1").html(result);
}
});
return false;
});
});
onclicking the main category some page will be executed and its output will be displayed in a html element.

Trouble Getting AJAX GET to work with whitepsace

I have a MYSQL table called orgs that has columns for name, city, zip, and state. I want an AJAX dropdown that populates another field on my page with the name of the cities when I select the name of the city from the dropdown. I currently have the dropdown for the city updating based on what state I have but when I try the call for the organizations name based on the city my code fails. Here's what I currently have.
AJAX to get the names of the cities:
function list(str)
{
if (str=="")
{
document.getElementById("list").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("list").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/list_org.php?q="+str,true);
xmlhttp.send();
}
AJAX to get the names of the organizations based on the cities:
function get_cities(str)
{
if (str=="")
{
document.getElementById("get_cities").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("get_cities").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
xmlhttp.send();
}
list_org.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$sql2="SELECT DISTINCT city FROM orgs WHERE state= '".$q."'";
$result2=mysqli_query($connection,$sql2);
if(!$result2){
die("Database query failed. " . mysqli_error($connection));
}
echo "<form>";
echo '<select name="get_cities" onchange="get_cities(this.value)">';
echo '<option value="">Select a city:</option>';
while($row2= mysqli_fetch_array($result2)){
echo '<option value="' . $row2['city']. '">'. $row2['city'].'</option>';
}
echo "</form>";
mysqli_close($connection);
?>
get_cities.php:
<?php include_once '../php/db_connect.php'; ?>
<?php
$q = strval($_GET['q']);
$q='CA';
$sql2="SELECT * FROM orgs WHERE state = '".$q."'";
$result=mysqli_query($connection,$sql2);
if(!$result){
die("Database query failed. " . mysqli_error($connection));
}
echo $q;
$link_address = '#';
echo '<div id="get_cities">';
while($row = mysqli_fetch_array($result))
{
echo "<ul>";
echo "<li><a href='".$link_address."' name='" . $row['id'] ."'>" . $row['name'] . "</a></li>";
echo "</ul>";
}
echo '</div>'
mysqli_close($connection);
?>
I thought the problem was probably that I was passing cities with whitespace in them (like "los angeles") but I've tried it with single name cities like "Buffalo" and nothing happens when I change my selection either. Any help would be greatly appreciated.
You are missing a </select> in list_org.php. Try to fix that one first, then escape your string.
Replace
xmlhttp.open("GET","../php/get_cities.php?q="+str,true);
to
xmlhttp.open("GET","../php/get_cities.php?q="+escape(str),true);

Error when using drop menu to change database value

When i select a drop menu option to change a value in my database to the selected value it gives this error:
SyntaxError: missing ) after argument list changeGroup("email#email.com")
Basically what im trying to do is I have an app that stores contacts, in the ungrouped contacts section it has the drop menu and when u select a value from it it submits the values and uses the value to update the database. I use the:
action='javascript:changeGroup(".$contactDetails.")
to tell the update statement which contact to update.
my code:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<!--Links to Javascript file for the for action to change the group of a contact-->
<script src="ajax.js" language="javascript"></script>
<?php
$contactDetails = $_GET['contactDetails'];
$cdquery="SELECT * FROM `contacts` WHERE `newEmail` = '$contactDetails'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
while ($row = mysql_fetch_assoc($cdresult))
{
echo "" . $row['newFname'] . " " . $row['newLname'] . "'s " . "Details:";
echo "<table>";
echo "<tr>";
echo "<th>Name:</th>";
echo "<th>Email Address:</th>";
echo "<th>Phone:</th>";
echo "<th>Postal Address:</th>";
echo "<th>Group:</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['newFname'] . " " . $row['newLname'] . "</td>";
echo "<td>" . $row['newEmail'] . "</td>";
echo "<td>" . $row['newPhone'] . "</td>";
echo "<td>" . $row['newAddress'] . "</td>";
echo "<td>" . $row['group'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
<select id='group' name='group' onchange='this.form.submit(value=this.options[this.selectedIndex].value)'>
<option>Select a group...</option>
<option value='Family'>Family</option>
<option value='Friends'>Friends</option>
<option value='Colleagues'>Colleagues</option></select>
group.</form>";
mysql_close($link);
?>
ajax function:
function changeGroup(str)
{
document.getElementById("content02").innerHTML="";
if (str=="")
{
document.getElementById("content02").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("content02").innerHTML=xmlhttp.responseText;
document.getElementById("content02").innerHTML = "";
}
}
xmlhttp.open("GET",'getChangeGroup.php?contactChange='+contactChange+'&group='+group,true);
xmlhttp.send();
xmlhttp.onreadystatechange = changeReload;
xmlhttp.send(null);
}
php:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<?php
$contactChange = $_GET['contactChange'];
$group = $_GET['group'];
$cdquery="UPDATE `contacts` SET `group` = '$group' WHERE `newEmail` = '$contactChange'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
mysql_close($link);
?>
I don't really know what your code does, nor do I have the patience to completely replicate it on my end, but as it stands you are passing a variable to your function, instead of a string, on this line:
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
To fix that, you need to quote your string as an actual string:
echo "<form action='javascript:changeGroup(\'".$contactDetails."\')' method='get'> Add contact to
I would assume this is your main issue. Without those quotes, javascript treats your echoed variable as a js variable, instead of a string.
In regards to your db interaction...
Also, you are using a deprecated.. and soon to be removed database interaction API. I recommend PDO to replace it, it prevents injection attacks and won't be removed in the near future, learn more about it here.

Where does code for a dynamic AJAX Submit button go? How do you architect a dynamic AJAX php/javascript webpage?

Here is my Question:
I have a dynamic list that displays X classes. when a class is selected, all the students of the class are displayed. When a user clicks "submit", I want to send an insert statement to the database. Where does the code for the submit button go?
My Attempt: Pseudocode/structure
Files placed in 1 folder on webserver: Index.php and getStudentList.php
Index.php
<script>
function showStudents(str)
blabla
xmlhttp.open("GET","getStudentList.php?q="+str, true);
xmlhttp.send();
</script>
...
<div>
html display goes here, as well as the form itself
</div>
getStudentList.php
<script>
logic for javascript goes here which connects to a db and inserts attendance info
</script>
<?php
connect to db
query students in class
echo attendance form
?>
Detailed Code:
Index.php
<!--start script for AJAX attendance display-->
<script>
function showStudents(str)
{
if (str=="") {
document.getElementById("attendanceForm").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("attendanceForm").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getStudentList.php?q="+str,true);
xmlhttp.send();
}
<script>
<div>
<?php
//identify teacher's classes
$school_connection = New school();
$arrayTeachersClasses = $school_connection->queryTeachersClasses($_SESSION['teacherID']);
//returns array of all classes taught
//echoes today's date
echo Date("l F d, Y");
//create list so teacher can pick class
echo "<form>";
echo "<select name = \"courses\" onchange = \"showStudents(this.value)\">";
echo "<option value=\"\">Select a class:</option>";
$i = 0;//counter
while ($row = $arrayTeachersClasses[$i]) {
echo "<option value=\"". $row[0] . "\">";
echo $row[1] . " ". $row[2] . "-L". $row[3] . " Room " . $row[4];
echo "</option>";
$i++;
}
echo "</select>";
echo "</form>";
/***
//Sample "Select a Class" list
<form>
<select name="users" onchange="function(this.value)">
<option value="">Select a class:</option>
<option value="0">09:00:00 BEG-L1 Room303</option>
<option value="1">TIME SUBJ-LEVEL ROOM</option>
<option value="2">ditto</option>
<option value="3">ditto</option>
</select>
</form>
*/
$teacherID = $_SESSION['teacherID'];
//echo $teacherID;
?>
</div>
<br />
<div id="attendanceForm">
<p><b>Attendance List:</b></p>
Please Select a Class
</div>
getStudentList.php
<script>
//Other JS stuff
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
$i = 0;//counter
var attendanceData = new Array();
//Get the data for each student
while ($row = $arrayStudentList[$i]) {
var studentID = $('input[name=' . $row[0] . ']');
if (studentID.val()=='') {
studentID.addClass('highlight');
return false;
} else studentID.removeClass('highlight');
$row[2] = studentID.val;
$attendanceData[$i] = $row;
$i++;
}
$row = $attendanceData[0];
$record = $row[2];
alert("My First JavaScript");
//cancel the submit button default behaviours
return false;
});
});
</script>
there are many ways of doing this...
Below are 2 simple solutions: with postback or through ajax.
Options 1 - Postback
when submit is clicked submit the form to the index page itself: leave form action blank or use $_SERVER['PHP_SELF']
in index.php prior to displaying anything check request type & params and save data
generate success/failure message and display
Option 2 - Ajax
create new page insertStudent.php
Add ajax functionality to form submit and send form to insertStudent.php. see jquery submit or reinvent the wheel for your project
In insertStudent.php save the student and return json status or (1/0)
handle the response in your ajax handler (step 2) to display success/failure message
Hoe this helps you with your homework ;-)

AJAX updating db, but not replacing <div>

So close, yet so far. There is a table that displays the status of trouble ticket's (submitted, open, closed), when the ID of a ticket is clicked, more info is displayed and a button is given to Open the ticket or Close it. The button has an onClick event that sends the AJAX to work, and the button works as far as updating the status of the ticket is concered. Howeever, upon update the in the display table that shows the Status should update as well, but does not.
Button:
if ($ticketarray['status'] == "0") {
// print option to open ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Open Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
if ($ticketarray['status'] == "1") {
// print option to close ticket
echo "<form>";
echo "<input type=\"button\" name=\"". $ticketarray['id'] ."\" value=\"Close Ticket\" onClick=\"statusChange(". $ticketarray['id'] .")\" />";
echo "</form>";
}
Table:
echo "<td name=\"statusholder\" style=\"padding: 0px;margin: 0px;\" /><div style=\"font-color: ". $fontcolor .";font-weight: bold;background-color: ". $statuscolor .";text-align: center;width: 100%;height: 100%;visibility: visible;\" name=\"statusdiv\">". statusTranslator($tixarray['status']) ."</div></td>";
AJAX:
function statusChange(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('statusdiv').style.visibility = hidden;
document.getElementById('statusholder').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","statuschange.php?id="+str,true);
xmlhttp.send();
}
STATUSCHANGE.PHP:
<?
include("./header.php");
if (isset($_GET['id'])) {
// valid request, get current status
$currentstatus = mysql_query("SELECT status FROM `table` WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("Cannot get current ticket status ". mysql_error());
$currentarray = mysql_fetch_assoc($currentstatus) or die("cannot make array ". mysql_error());
if ($currentarray['status'] == "0") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='1' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #FFFF00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Open</div>";
}
if ($currentarray['status'] == "1") {
// currently Submitted, make Open
mysql_query("UPDATE `table` SET status='2' WHERE id='". mysql_real_escape_string($_GET['id']) ."'") or die("cannot update status ". mysql_error());
// send reformatted status div
echo "<div style=\"font-color: #000;font-weight: bold;background-color: #33CC00;text-align: center;width: 100%;height: 100%;\" name=\"statusdiv_updated\">Completed (Closed)</div>";
}
} else {
echo "nothing to do here";
}
?>
On this line
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
remove the
&& xmlhttp.status==200
and it should work fine :-)

Categories