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>
Related
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>";
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.'';
I have been looking through the questions on here and cant find an exact answer to what i am after :( but i have managed to get something.
i have a form select field which i populate from a db query
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
and then there are currently 2 other textboxes (might increase eventually) which i want to populate when the above select box value is changed/selected
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
so i have an onchange function on my select box which is this
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and my formdata.php file is like so
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
which is making the ajax call correctly and returning the data expected but i now need help to populate the textbox values?
can anyone please help me with this, have literatly spent ages trying to figure it out, im not familiar with javascript/json so not sure where to begin
i want the company_name textbox value to be set to $cName; and
company_email textbox value to be set to $cWeb;
appreciate any help
Luke
ok the solution that i used, for anyone else wanting to know how i solved it is
my index.php which contains the javascript and the form code
javascript code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").value="";
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)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").value = data[i].name;
document.getElementById("company_email").value = data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and the form code
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />
then my formdata.php
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['businessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
thats it, thanks to charlietfl for your help!
hope this helps someone :)
Here's an example with PHP and JQuery. If you are not familiar with JQuery, I suggest you take some time to digg into that before going on with your ajax, it's definitely gonna worth it. JQuery have methods like get and ajax to do async request to the server.
Now, heres some jquery we used to get JSON data from the server.
var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
function(data){
$("#currentId").val(data.ID);
$("#nomActivite").val(data.Nom);
$("#Description").val(data.Description);
$("#DateEvent").val(data.Date);
});
$("#currentId").val(data.ID); , this says : find the element with the id currentId in the DOM, and change it's value to the property ID of the data received from the ajax call.
On the PHP side, they had
<?php
header('Content-Type: application/json');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$title = $_GET["title"]; // we received this from the json call
$query = " select a.ActiviteID as ActiviteID , rtrim(a.Nom) as Nom, a.Description from activites a inner join .....' ";
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
'ID' => $ligne["ActiviteID"],
'Nom' => $ligne["Nom"],
'Description' => $ligne["Description"],
'Date' => $date
);
mysql_close();
echo (json_encode($data));
?>
I have an AJAX script running on my website that is supposed to update a dependent dropdown menu (a SELECT options menu) after a previous dropdown menu onchange event happens.
When I click on the first dropdown, the second dropdown does seem to be populated with the correct values from a MySQL database query. However, under my values I also seem to be pulling in the contents on the entire HTML webpage as a whole.
I'd like to know how to only bring in my values without loading the whole webpage again inside of my SELECT options menu.
My Javascript:
<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_aris=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp_aris=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_aris.onreadystatechange=function()
{
if (xmlhttp_aris.readyState==4 && xmlhttp_aris.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp_aris.responseText;
}
}
xmlhttp_aris.open('GET','http://mywebdomain.com?ajax=true&q='+str,true);
xmlhttp_aris.send();
}
</script>
My PHP code:
// begin my ghetto code
if ($_GET['ajax'] == 'true') {
$q = $_REQUEST["q"];
$con = mysqli_connect('localhost','db_user','db_pass','db_name');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql='SELECT DISTINCT
employees.firstName,
employees.lastName
FROM
sales_reps
INNER JOIN employees ON sales_reps.employeeId = employees.employeeId
INNER JOIN sales_campaign ON sales_campaign.salesCampId = sales_reps.saleCampId
WHERE
sales_campaign.marketId = '.$q.' AND
employees.isactive = 1';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['firstName'] . '">'
. htmlentities($row['firstName']) .' '.htmlentities($row['lastName']) .'</option>';
}
mysqli_close($con);
}
// end my ghetto code
My code on the page with the dropdown menus:
<select id="frm-marketid" name="frm-marketid" onchange="showUser(this.value)">
<option value="">Choose a Market</option>
<option value="74">Annapolis</option>
<option value="61">Anne Arundel</option>
<option value="26">Aventura</option>
<option value="63">Baltimore</option>
</select>
<br/>
<select id="txtHint"><b>Person info will be listed here.</b></select>
just kill your script after you output your response for ajax
...
}
mysqli_close($con);
exit;
}
...
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;
}