3 Drop Downs chain using ajax mysql - php

I have 3 Pages Index.php findasset.php and findid.php. I have 2 dropdowns and the last value will be echo out to another part of the page. I am using ajax to query the other dropdowns and it is partially working.
Most of it is dynamic and working besides device_category_name='$cId' on the findid page which should be replaced with $category but I wanted to show code as a working model. I think the original start of my problem is on findasset page $category= isset($_GET['category']);
When I try to echo out the variable on findid it echoes a "1" and not the word
The index page has a dropdown pulled from mysql database that is working just fine. I have tagged the code as best as I could describe.
Here is partially Working example. If you select Category-Drawing then either of the Assets it works, but it is because of on the findid page the query is partically hard coded and I dont want it to be hardcoded.
I know, I am so close to getting this figured out but I am stuck. Could you help me out?
Index.php
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getcategory(category) {
var strURL="findasset.php?category="+category;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('assetdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getid(category,asset) {
var strURL="findid.php?category="+category+"&asset="+asset;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('iddiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Category</td>
<td width="150"><select name="category" onChange="getcategory(this.value)">
<?
require "config.php";// connection to database
$query = "SELECT DISTINCT device_category_name FROM fgen_structures ORDER BY device_category_name ASC";
$result = mysql_query($query);
while ($myrow = mysql_fetch_array($result))
{
echo "<option value='$myrow[device_category_name]'>$myrow[device_category_name]</option>";
}
?>
</select></td>
</tr>
<tr style="">
<td>Asset</td>
<td ><div id="assetdiv"><select name="asset" >
<option>Select Category First</option>
</select></div></td>
</tr>
<tr style="">
<td>ID</td>
<td ><div id="iddiv"></div></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>
findasset.php
$category= isset($_GET['category']);// Could be the Start of the PROBLEM
$cate=$_GET['category'];
require "config.php";// connection to database
$query="SELECT * FROM fgen_structures WHERE device_category_name='$cate'";
$result=mysql_query($query);
?>
<select name="asset" onchange="getid(<?=$category;?>,this.value)">
<option>Select State</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value=<? echo $row['device_type_name'];?>><? echo $row['device_type_name'];?></option>
<? } ?>
</select>
findid.php
<?
$category=isset($_GET['category']); // This is where I think the problem is as well!!!!
$asset=isset($_GET['asset']);
$cate=$_GET['category'];
$assets=$_GET['asset'];
$cId='Drawing'; //If Hard Coded works
require "config.php";// connection to database
$query="SELECT * FROM fgen_structures WHERE device_category_name='$cId' AND device_type_name='$assets'"; // Currently hardcoded with $cid and it works but I need it dynamic with $cate or $category
$result=mysql_query($query);
while($row=mysql_fetch_array($result)) {
echo $row['fgen_structure_id'];
//echo $category; // This displays a 1 ??
} ?>

I think your problem is, you don't understand what "isset()" is doing:
$category=isset($_GET['category']);
http://php.net/isset determines weither a variable or an index exists (and is not NULL), the return value of isset is boolean, this mean either true or false. In your case it seems to be true, because your echo shows an 1.
I think you try to do this:
$category=isset($_GET['category']) ? $_GET['category'] : null;
On the other hand, you have heavy security issues in your code
$query="SELECT * FROM fgen_structures WHERE device_category_name='$cId' AND device_type_name='$assets'";
You can't just use $assets unfiltered. Please google for SQL Injection for more informations.

Related

I am getting Notice: Undefined index: select_dept when using ajax call

i want to display doctors name corresponding to the speciality so i have used ajax
when speciality is selected corresponding doctors name will also display
i am getting error like this and doctors list is not showing up
Notice: Undefined index: select_dept in C:\wamp\www\xx\get_specialist.php
on line 2
Call Stack
# Time Memory Function Location
1 0.0012 140616 {main}( ) ..\get_specialist.php:0
my form code
<select name="select_dept" id="select_dept"
class="textBox" style="width:180px" onChange="getSpecialist(this.value)">
<option value="">Select Department</option>
<?php
include("db_conexn.php");
$res=mysql_query("SELECT * FROM imh_departments");
while($rowCat2 = mysql_fetch_array($res)){?>
<option value="<?php echo $rowCat2['depart_id']?>">
<?php echo $rowCat2['department_name'];?></option>
<?php }?>
</select>
<div id="statediv">
<select name="doct" >
<option>Select Doctor</option>
</select>
</div>
My ajax code
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getSpecialist(countryId)
{
var strURL="get_specialist.php?country="+countryId;
var req = getXMLHTTP();
if (req){
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
get_specialist.php code
<?php
$country=$_REQUEST['select_dept'];
include("db_conexn.php");
$query="SELECT doct_id,doct_name FROM imh_doctors WHERE depart_id='$country'";
$result=mysql_query($query);
?>
<select name="doct" >
<option>Select Doctor</option>
<?php while ($row=mysql_fetch_array($result)){?>
<option value=<?php echo $row['doct_id'];?>><?php echo $row['doct_name'];?></option>
<?php } ?>
</select>
your
$country=$_REQUEST['select_dept'];
should be
if(isset($_REQUEST['country'])) {
$country=$_REQUEST['country'];
// rest of db code
}
Please note that your code is open to SQL injection and should use mysqli and mysqli_real_escape_string instead.
You are assigning $country to select_dept and you may want to change that.
$country = $_REQUEST['country'];

Delete selected records from database onClick

I want to delete a record from database on click and this is what I have tried:
delete.js
function oki(){
mysql_query("DELETE FROM topics WHERE id='58'");
}
Button:
<script type="text/javascript" src="delete.js"></script>
<?php
include_once("connect.php");
?>
<button onClick="oki();">Del</button>
Please help me I cant find out how to do this.
Just tell me if you need any more information.
If you just want to delete from a link, don't care about page reload etc... then it's already answered here:
php delete mysql row from link
But it sounds like you want to click a button, and it'll delete the row without navigating you away from the page you're on, in which case you'll want to look into using some form of ajax.
You've not provided enough of your code so can't help you with updating the display after you've performed your action, but the basis would probably look something like this (untested)
delete.php
<?php
include_once("connect.php");
if ($_GET['mode'] == 'delete') {
$row_id = (int)$_POST['row_id'];
mysql_query("DELETE FROM topics WHERE id=" . $row_id);
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1 /jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.delete-row').click(function() {
$.post('delete.php?mode=delete', { row_id: $(this).data('row_id')}).done(function(data) {
// Reload your table/data display
});
});
});
</script>
<button class="delete-row" data-row_id="58">Delete</button>
I would HEAVILY advise against using mysql_ functions, use PDO or MySQLi instead. Go back to basics and learn how PHP and javascript can interact with each other, as there's something not right there in your knowledge.
Edit (additional OCD):
You should also be considering other things, can anyone delete any row? If only certain people should have permission, you should verify that the currently logged in user should be allowed to delete that particular row prior to deleting it.
<input type="button" onclick="deleteme(<?php echo $row['id']; ?>)"> // fetch from database
<script language="javascript">
function deleteme(delid)
{
window.location.href='delete.php?del_id='+delid+'';
return true;
}
</script>
delete.php
$select="delete from tbl_category where id='".$_GET['del_id']."'";
$query=mysql_query($select) or die($select);
Sorry for my bad english
First of all create file with php extensions and function you create its php's function not javascript, so code this one.
Delete
Create delete.php file and code this one
if(isset($_GET['id'])) {
#mysql_query("DELETE FROM topics WHERE id = '".$_GET['id']."'");
header("location: index.php");
exit();
}
PHP
$ids = array_map('intval', json_decode($_GET['id']));
mysql_query("DELETE FROM topics WHERE id in (" . implode(',', $ids) . ")");
and in javascript (using jQuery)
function oki() {
var checked = $('.row:checked');
var ids = checked.map(function() { return $(this).val(); });
$.get('delete.php', {id: JSON.stringify(ids)}, function(response) {
checked.remove();
});
}
and your html would be
Row with id 10: <input type="checkbox" class="row" value="10"/>
Row with id 20: <input type="checkbox" class="row" value="20"/>
Row with id 30: <input type="checkbox" class="row" value="30"/>
Row with id 40: <input type="checkbox" class="row" value="40"/>
<button onClick="oki();">Del</button>
This is what I did to delete data without leaving page or reload page:
In some.php:
<?php
include"../connect.php";
// for simple security need change to improve
Session_start();
$n=rand(1,99);
$uid=md5($n);
$_SESSION['uid']=$uid
// end
?>
<script>
function getXMLHTTP() { //fuction to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getData(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('divResult').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<input name="button" type="button" value="Clear Data" onClick="getData('deldata.php?id=58&uid=<?=$uid?>')">
<div id="divResult"></div>
In deldata.php:
<?php
Session_start();
include"../connect.php";
$idd=$_REQUEST['id'];
$uid=$_REQUEST['uid'];
$sc=$_SESSION['uid'];
//check for simple security
if($sc==$uid){
mysqli_query("DELETE FROM topics WHERE id='$idd'");
echo "Data deleted":
}
?>
You can also use this for dynamic row for multiple "Delete" button.
Here is my solution:
<?php
$query="select * from product limit ".$offset. " , " .$perpage;
$result=mysql_query($query);
?>
<center>
<table border="2">
<tr>
<th>Category Name</th>
<th>Product Name</th>
<th>Product Description</th>
<th>Product Image</th>
<th>Product Actual image</th>
<th>Product Discount</th>
<th>Product Selling Price</th>
<th>Update/Delete</th>
</tr>
<?php while ($row=mysql_fetch_array($result)){?>
<tr>
<td><?php echo $row['pro_catagory'];?></td>
<td><?php echo $row['pro_name'];?></td>
<td><?php echo $row['pro_des'];?></td>
<td><img src="Img/<?php echo $row['pro_image'];?>" width="100" height="100" ></td>
<td><?php echo $row['pro_actual'];?></td>
<td><?php echo $row['pro_dis'];?></td>
<td><?php echo $row['pro_price'];?></td>
<tdDelete</td>
?>
In delete.php
<?php
$con=mysql_connect('localhost','root','');
if(!$con)
{
die('could not connect' .mysql_error());
}
mysql_select_db("jaswinder", $con);
$Query="delete from product where pro_id=".$_REQUEST['pid'];
$result=mysql_query($Query);
?>

Javascript popup selector + PHP

I have, with the help of the SO community written a javascript and php page that allows me to pass a value from the popup page back to the parent page.
This works 100% on internet explorer but not in google chrome or on my ipad / galaxt tablet.
Any idea on how this can be corrected? Any help appreciated as always.
Below is portions of my code from the parent page(newsale.php) and the popup page(sku.php). I know that other methods are recommended over using popup but I need to get this solution working with the popup page for application reasons.
newsale.php Parent Page (Code snippets, not entire page)
<script type="text/javascript">
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=1000,toolbar=1,resizable=1,scrollbars=yes,height=200,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
</script>
<table>
<tr id="r1">
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value)" <? if($rows>0){echo "value=".mysql_result($resultorder,0,1);} ?>><img src=q.png name="choice" onClick="selectValue('sku1')" value="?">
</td>
</tr>
<tr id="r2">
<td>
<input size=10 type=number id=sku2 name=sku2 onchange="showUser(2, this.value)" <? if($rows>1){echo "value=".mysql_result($resultorder,1,1);} ?> ><img src=q.png name="choice" onClick="selectValue('sku2')" value="?">
</td>
</tr>
</table>
sku.php Popup Page (entire page)
<?
$con = mysql_connect('localhost', 'username', 'password');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("DBName", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function AjaxFunction(cat_id) {
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if (httpxml.readyState == 4) {
var myarray = eval(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for (j = document.testform.subcat.options.length - 1; j >= 0; j--) {
document.testform.subcat.remove(j);
}
for (i = 0; i < myarray.length; i++) {
var optn = document.createElement("OPTION");
optn.text = myarray[i];
optn.value = myarray[i];
document.testform.subcat.options.add(optn);
}
}
}
var url="dd.php";
url = url+"?cat_id="+cat_id;
url = url+"&sid="+Math.random();
httpxml.onreadystatechange = stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
<script type="text/javascript">
function sendValue(value)
{
var e = document.getElementById("subcat");
value = e.options[e.selectedIndex].value;
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<script type="text/javascript">
function updateinput(){
var e = document.getElementById("subcat");
var catSelected = e.options[e.selectedIndex].value;
document.getElementById("copycat").value=catSelected;
}
</script>
<form name="testform">
Category: <select name=cat id=cat onchange="AjaxFunction(this.value);" style="width=300"> <br>
<option value='' style="width=300">Select One</option>
<br>
<?
require "config.php";// connection to database
$q=mysql_query("select * from categories");
while($n=mysql_fetch_array($q)){
echo "<option value=$n[cat_id]>$n[category]</option>";
}
?>
</select>
<br><br>
Pack Code:
<select name=subcat onchange="updateinput();" >
<br><br>
</select>
<br><br>
<input type=hidden name=copycat id=copycat >
<td><input type=button value="Select" onClick="sendValue(document.getElementById(copycat))" /></td>
</form>
dd.php (for dynamic drop down list)
<?
$cat_id=$_GET['cat_id'];
require "config.php";
$q=mysql_query("select concat(packcode,', ',description) as details from skudata where cat_id='$cat_id'");
echo mysql_error();
$myarray=array();
$str="";
while($nt=mysql_fetch_array($q)){
$str=$str . "\"$nt[details]\"".",";
}
$str=substr($str,0,(strLen($str)-1)); // Removing the last char , from the string
echo "new Array($str)";
?>
I dont think dd.php has any influence on the functionality of the parent popup relationship but have included it so you can follow the code.
As mentioned this works 100% on Internet explorer but not in google chrome or my ipad.
When you use
document.getElementById("subcat");
then you should also have an element with such an id. Your
<select name=subcat onchange="updateinput();" >
won't do with browsers like chrome, firefox, konqueror and probably lots of others. Use
<select id="subcat" onchange="updateinput();" >
instead.
Unfortunately, I can't get your code to work so I can't test this, but changing
window.opener.updateValue(parentId, value);
to
window.opener.contentWindow.updateValue(parentId, value);
or
window.opener.window.updateValue(parentId, value);
may solve this.
If it doesn't, maybe you can post the errors that are showing from the Chrome console and explain better what exactly doesn't work.
In below function also,you called for subcat.
function sendValue(value)
{
var e = document.getElementById("subcat");
}
along with one mentioned by Themroc.
You should first have an id="subcat".
Still you getting some problem , post the error.
Thanks.

AJAX Multiple Drop Downs

I'm looking off of this site to make a multiple drop down: Roshan's Blog
And most of it is working, I'm just having a problem with the 3rd drop down box.
(Dropdown1: Clients, Dropdown2:Location, Dropdown3:Zone)
On my page so far, if I look at the source, after selecting the first dropdown(Client1), the second dropdown statement says:
<select style="width: 150px;" id="add-event-dialog-location" name="add-event-dialog-location" onchange="getZone(Client1,this.value)">
Which is what I need, but now, when I click on one of the options in the second drop down, it is not placing through the getZone() script. The 'zonediv' is not changing, and I'm not sure if the rest is going through or not. If I load the getZone.php by itself and place in my own GET statements into the URL, I get results, but I can't get them within the page I'm calling the dropdowns from.
I'm probably just missing something small, but I've been looking at it so long, that I just can't figure it out.
The HTML:
<select style="width: 150px;" name="add-event-dialog-client_name" id="add-event-dialog-client_name" onchange="getLocation(this.value)">
<?php
echo "<option selected='selected' disabled='disabled'>-Client Name-</option>";
$result = mysql_query("SELECT DISTINCT client_name FROM spc_clients");
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['client_name']."'>".$row['client_name']."</option>";
}
?>
</select>
<p id="locationdiv">
<select style="width: 150px;" name="add-event-dialog-location" id="add-event-dialog-location" disabled="disabled">
<option>Select Client First</option>
</select>
</p>
<p id="zonediv">
<select style="width: 150px;" name="add-event-dialog-zone" id="add-event-dialog-zone" disabled="disabled">
<option>Select Location First</option>
</select>
</p>
Both of the JS Functions:
function getLocation(client_name) {
var strURL="display/getLocation.php?client_name="+client_name;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('locationdiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
function getZone(client_name,location) {
var strURL="display/getZone.php?client_name="+client_name+"&location="+location;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('zonediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
getLocation.php:
<?php
include 'connect.php';
$client = $_GET['client_name'];
$query="SELECT location FROM spc_clients WHERE client_name='$client'";
$result=mysql_query($query) or die(mysql_error());
?>
<select style="width: 150px;" id="add-event-dialog-location" name="add-event-dialog- location" onchange="getZone(<?=$client?>,this.value)">
<option selected='selected' disabled='disabled'>-Location-</option>
<?php
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['location']."'>".$row['location']."</option>";}
?>
</select>
getZone.php:
<?php
include 'connect.php';
$client = $_GET['client_name']; echo $client;
$location = $_GET['location']; echo $location;
$query="SELECT zone FROM spc_clients WHERE (client_name='$client' && location='$location')";
$result=mysql_query($query) or die(mysql_error());
?>
<select style="width: 150px;" id="add-event-dialog-zone" name="add-event-dialog-zone">
<option selected='selected' disabled='disabled'>-Zone-</option><option><?php
while($row = mysql_fetch_array($result)){
echo $row['zone'];}
?>
</option>
</select>
Try putting quotes around Client1 -- without quotes, javascript thinks it's a variable, and since you haven't defined any variable called Client1, you're getting an error. Putting quotes around it makes it a string, which is what you want to pass to getZone().
Try putting this in getLocation.php:
<select style="width: 150px;" id="add-event-dialog-location" name="add-event-dialog- location" onchange="getZone('<?=$client?>',this.value)">
If any of your Client names have quotation marks in them, you'll have to make sure to escape them, see here for how to do that:
Pass a PHP string to a JavaScript variable (and escape newlines).

calling DB from javascript throwing error

i have a simple php page postArticle.php with two dropdown list with categories and subcategories and subcategories generates on the basis of categories.
for generating subcategories i am using java script from which i am calling another php file(data.php)
the code postarticle.php is
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function getSubCategories(l1,l2)
{
var response;
var xmlHttp;
if(l1.selectedIndex>=1)
{
try{
var id=document.getElementById('listCategory').value;
//alert("hello "+id);
l2.disabled=false;
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");
}
//alert("hello 1");
xmlHttp.open("POST","data.php?q="+id,true);
//alert("id passed is : " +id);
xmlHttp.onreadystatechange = function(){
//alert("inside fn1");
if (xmlHttp.readyState == 4)
{
//alert("inside if fun");
//alert(xmlHttp.responseXML.getElementsByTagName("div")[0]);
//alert("response text : "+xmlHttp.responseText);
response=xmlHttp.responseText;
}
//alert("inside fn2");
}
//alert("hello 3");
xmlHttp.send("data.jsp?q="+id);
//alert('hello 4');
var resArray=new Array();
//alert('hello 5');
response=response.replace(/^\s+|\s+$/g,"");
resArray=response.split("#");
//alert('hello 6');
//alert("response array : "+resArray);
for(x in resArray)
{
//alert(resArray[x].substring(0, resArray[x].indexOf("*")));
//alert(resArray[x].substring(resArray[x].indexOf("*")+1));
if(resArray[x].substring(0, resArray[x].indexOf("*"))!=" " && resArray[x].substring(resArray[x].indexOf("*")+1)!="")
{
var OptNew = document.createElement('option');
OptNew.text = resArray[x].substring(resArray[x].indexOf("*")+1);
OptNew.value = resArray[x].substring(0, resArray[x].indexOf("*"));
try
{
//for IE earlier than version 8
l2.add(OptNew,l2.options[null]);
}
catch (e)
{
l2.add(option,null);
}
}
}
}catch(e){alert(e.toString());}
}
else
{
return;
}
var newOpt = new Option(selText[i], selValues[i]);
theSel.options[i] = newOpt;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<table border="1" width="100%">
<tr id="header" >
<td height="30%" width="100%" colspan="3">
<?php include("Header.php"); ?>
</td>
</tr>
<tr id="body">
<td height="65%" width="15%" valign="center">
<table width="100%">
<tr><td>
<?php include("LeftPanel.php"); ?>
</td>
</tr>
</table>
</td>
<td height="65%" width="75%" valign="center">
<form method="post" action="PostArticle_Back.php">
Title: <input type="text" name="txtTitle" id="txtTitle">
<br>
Content : <textarea id="txtContent" name="txtContent" rows="5" cols="50"></textarea>
<br>
<p>select Category :</p>
<select id="listCategory" name="listCategory" onchange="getSubCategories(listCategory,listSubCategory)">
<option value="0">Select Category</option>
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("articles_db",$con);
$result = mysql_query("select CATEGORY_ID, CATEGORY_NAME from TBL_CATEGORIES");
while($row = mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['CATEGORY_ID'] ; ?>" > <?php echo $row['CATEGORY_NAME'] ; ?>
</option>
<?php } ?>
</select>
<br>
<p>select SubCategory :</p>
<select id="listSubCategory" name="listSubCategory" disabled="true">
<option value="0">select Subcategory</option>
</select><br>
<input type="submit" value="Post Article"/>
</form>
</td>
<td height="65%" width="10%" valign="center">
Right panel
</td>
</tr>
<tr id="footer">
<td height="5%" colspan="3">
Footer
</td>
</tr>
</table>
</body>
</html>
but it throws an error
TypeError : undefined is null or not an object
the problem what i find till now is that the data.php is taking time to send response
if(xmlHttp.readyState == 4) is taking time to execute.
because when i add alert statements in between code it works fine.
what i tried till now:
i tried to add while loop outside if condition but broweser gives a warning :
script is making your webpage slow
i tried to put the code(the code for adding repose to drop down list) in if(xmlHttp.readyState == 4) condition but it did not gave any response.
Tip 1
I don't really get what that is your problem, but if you need to wait to get the value you can use Async=false.
xmlHttp.open("POST", "data.php?q="+ id, false);
Then you dont need the xmlHttp.onreadystatechange = function(){ ... }, the code will wait for the response, and the rest of the Javascript will stop execute until the response is fetched.
Tip 2
If you still want other Javascript code to execute (Async = true) you can put
var resArray=new Array();
//alert('hello 5');
response=response.replace(/^\s+|\s+$/g,"");
resArray=response.split("#");
...more code...
}
}
in the xmlHttp.readyState == 4 block.
if (xmlHttp.readyState == 4)
{
response=xmlHttp.responseText;
//Put the code here
}
I had done like this.
Other things
Why do you use "POST"? You dont send any POST data.
xmlHttp.send("data.jsp?q="+id); should be xmlHttp.send("q="+id); if you want to fetch $_POST['q']. But you already send id like an GET request in xmlHttp.open("POST","data.php?q="+id,true);, so why send it again with POST?
And please indent your code correctly.
_
Btw, what is AJAX without Asynchronousing? Javascript And XML? :P
EDIT:
Yay, my first "Correct answer" :)

Categories