Can I use more than one function in one script? - php

I'm trying to use Ajax, PHP, and MySQL together to make a form element, drop-down style select input be able to select an option and have the ajax sent data through the script to the database and back to the page to a separate div. I have most of the code for this figured out. My issue now is this.
I have three drop-down menus that 1 would like to have go to this script. It would then go to three different $GET scripts depending on which menu it was selected from.
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send(); }
</script>
The three select elements I have are accompanied with onchange functions.
<select name="characters" onchange="showCharacter(this.value)">
<select name="towers" onchange="showTowers(this.value)">
<select name="enemies" onchange="showEnemies(this.value)">
The PHP code I have for this script is this:
<?php
include("dbinfo.inc.php");
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
mysql_select_db("db1801445-main", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
$q=$_GET["q"];
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Description</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['Description'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Idk how else to do this so can you guys help me?

I agree that using jQuery would make your life easier, but to address your question:
You could make that JS code more general so it would be easier to reuse:
<script type="text/javascript">
function doAjax(ajaxFunction, 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","getuser.php?q="+str+"func="+ajaxFunction,true);
xmlhttp.send(); }
</script>
And then change you PHP do this:
<?php
$sFunction = $_GET["func"];
$sQ =$_GET["q"];
switch($sFunction){
case 'showUser':
//code here;
break;
case 'showTowers':
//code here;
break;
case 'showEnemies':
//code here;
break;
case 'showCharacters':
//code here;
break;
}
?>
And back on the frontend:
<select name="characters" onchange="doAjax('showCharacter',this.value)">
<select name="towers" onchange="doAjax('showTowers',this.value)">
<select name="enemies" onchange="doAjax('showEnemies',this.value)">

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

retrieve sql data & print it into form field

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.

Retrieve mySQL Data On Radio Button Click

Through some very much appreciated help from users of this site I've been able to put together a script that upon a radio button click will populate a table with user details.
I thought that I'd be able to adapt it even further, but, quite possibly because of my lack of experience, unfortunately I've come across another problem, hence why I've added a new post.
Pulling the data from a mySQL database I'm using the code below to create a list of dates with an associated radio button.
<html>
<head>
<script type="text/javascript">
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($userid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$userid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Then with the following code I want to populate a table with the associated 'findname' details for the radio button clicked.
<?php
$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($sql))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I can get the first part of the script to work, i.e. the creation of the date list and radio buttons, but when I select the radio button, the table appears with the correct column heading, but I receive the following error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /homepages/2/d333603417/htdocs/development/getuser2.php on line 21 with line 21 being this line: while($row = mysql_fetch_array($sql)).
As I said earlier the other users that answered my first post were great, but I just wondered if someone could perhaps have a look at this please and let me know where I've gone wrong.
Updated Code
Form
<html>
<head>
<script type="text/javascript">
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","getuser2.php?="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.findid, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.locationid=detectinglocations.locationid AND finds.userid = 1 GROUP By dateoftrip ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
echo"<table>\n";
while (list($findid, $dateoftrip) =
mysql_fetch_row($result))
{
echo"<tr>\n"
.
"<td><input type='radio' name='show' dateoftrip value='{$findid}' onClick='showUser(this.value)'/></td>\n"
."<td><small>{$dateoftrip}</small><td>\n"
."</tr>\n";
}
echo'</table>';
}
?>
<br />
<div id="txtHint"></div>
</body>
</html>
PHP
<?php
//$q=$_GET["q"];
$con = mysql_connect('hostname', 'username', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('database', $con);
$sql="SELECT * FROM finds";
$result = mysql_query($sql);
// This is helpful for debugging
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "<table border='1'>
<tr>
<th>Find Name</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['findname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
while ($row = mysql_fetch_array($result))
not
while ($row = mysql_fetch_array($sql))
mysql_fetch_array accepts a mysql result object (which you get from the mysql_query function call), not a string
In $row = mysql_fetch_array($sql)
$sql is a string, you should use $result instead, which is a mysql_result object.

value not getting posted from the element generated by ajax class

This is the HTML form
echo "<tr><td>Course</td><td><select name='Course' onchange='branch_selector(this.value)'>";
echo "<option value='B.Tech'>B.Tech</option>";
echo "<option value='M.Tech'>M.Tech</option>";
echo "<option value='MBA'>MBA</option>";
echo "<option value='MCA'>MCA</option>";
echo "</select></td></tr>";
echo "<tr><td><div id='branch_div_name'></div></td><td><div id='branch_div'></div></td></tr>";
this is the javascript code
function branch_selector(val) {
if(val=='B.Tech' || val=='M.Tech') {
show_name('branch_div_name','Branch');
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('branch_div').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","branch_selector.php",true);
xmlhttp.send();
}
else {
document.getElementById("branch_div").innerHTML="";
disappear_name('branch_div_name');
}
}
This is the PHP code running at the backened
$result = mysql_query("SELECT DISTINCT Branch FROM student_main ORDER BY Branch ASC") or die(mysql_error());
echo "<select name='Branch' id='Branch' onchange='harb()'>";
while($row = mysql_fetch_array($result)) {
if($row[0]=='' or $row[0]=='N/A') {
continue;
}
else {
echo "<option value='".$row[0]."'>".$row[0]."</option>";
}
}
echo "</select>";
The dropdown is generated without any problem. But when the form is submitted the $_POST['Branch'] is not set.
Please help
Ok, I have solved this issue, The solution is not the best but its getting the job done.
I am using now a hidden field and the value is this field is set according to the value of Branch of. The value is set using Javascript when user click on submit.
Its working fine, no issue whatsoever but if someone have better solution, please share.

Categories