Delete selected records from database onClick - php

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

Related

Confirm button before running deleting routine from website

I have a page on my website that is dynamically created with information from an SQL database. As well as the data being displayed a delete link is also created for each record which links to a php file called deleteRecord.php that deletes that record from the database.
Is there any way I can incorporate a confirmation message so that when the Delete link is clicked it will only run the deleteRecord.php file if the response is Yes?
You could use JavaScript. Either put the code inline, into a function or use jQuery.
Inline:
Delete
In a function:
Delete
and then put this in <head>:
<script language="JavaScript" type="text/javascript">
function checkDelete(){
return confirm('Are you sure?');
}
</script>
This one has more work, but less file size if the list is long.
With jQuery:
Delete
And put this in <head>:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
$("a.delete").click(function(e){
if(!confirm('Are you sure?')){
e.preventDefault();
return false;
}
return true;
});
});
</script>
You have 2 options
1) Use javascript to confirm deletion (use onsubmit event handler), however if the client has JS disabled, you're in trouble.
2) Use PHP to echo out a confirmation message, along with the contents of the form (hidden if you like) as well as a submit button called "confirmation", in PHP check if $_POST["confirmation"] is set.
Call this function onclick of button
/*pass whatever you want instead of id */
function doConfirm(id) {
var ok = confirm("Are you sure to Delete?");
if (ok) {
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) {
window.location = "create_dealer.php";
}
}
xmlhttp.open("GET", "delete_dealer.php?id=" + id);
// file name where delete code is written
xmlhttp.send();
}
}
You can do it with an confirm() message using Javascript.
Try this one :
<script type="text/javascript">
var baseUrl='http://example.com';
function ConfirmDelete()
{
if (confirm("Delete Account?"))
location.href=baseUrl+'/deleteRecord.php';
}
</script>
echo '<a type="button" onclick="ConfirmDelete()">DELETE ACCOUNT</a>';
<?php
$con = mysqli_connect("localhost","root","root","EmpDB") or die(mysqli_error($con));
if(isset($_POST[add]))
{
$sno = mysqli_real_escape_string($con,$_POST[sno]);
$name = mysqli_real_escape_string($con,$_POST[sname]);
$course = mysqli_real_escape_string($con,$_POST[course]);
$query = "insert into students(sno,name,course) values($sno,'$name','$course')";
//echo $query;
$result = mysqli_query($con,$query);
printf ("New Record has id %d.\n", mysqli_insert_id($con));
mysqli_close($con);
}
?>
<html>
<head>
<title>mysql_insert_id Example</title>
</head>
<body>
<form action="" method="POST">
Enter S.NO: <input type="text" name="sno"/><br/>
Enter Student Name: <input type="text" name="sname"/><br/>
Enter Course: <input type="text" name="course"/><br/>
<input type="submit" name="add" value="Add Student"/>
</form>
</body>
</html>
Another method using both onlcick & form submit button with php record id value (record to be delete).
Use php code to get the record ID to be deleted. This is working for me.
<form action="deleteRecord.php" method="POST">
<button onclick="return confirm('Are you sure! want to delete?')" type="submit" name="id" value="<?=$record['id'];?>" >Delete</button>
</form>
deleteRecord.php example file
<?php
$con=mysqli_connect("localhost","root","","dbname") or die(mysqli_error($con));
if(isset($_POST['id']))
{
$id = mysqli_real_escape_string($conn, $_POST['id']);
$query = "DELETE FROM table_name WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
}
mysqli_close($con);
if($query_run)
{
echo "Deleted Successfully";
exit(0);
}
else
{
echo "Not Deleted";
exit(0);
}
?>

3 Drop Downs chain using ajax mysql

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.

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

Commenting System - Ajax, Php & MySql

I've succeeded to write a simple commenting system with a form of 2 fields: name and comment. When the user inters values and presses submit it simply adds the comment to the current page using Ajax (without loading the whole page).
Now, I need also to add the ability of "Deleting Comment", but I have no idea how can I implement that.
If you take a look at my code bellow you would notice that when loading the page I printed all the existing comments, and when adding new ones I simply added them to the HTML code by this sub-code:
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
I thought of declaring an array that holds the values of all the comments with an additional value for each one "active".
When this value is trua I print the current comment, else I dont.
I've not succeeded to implement that, besides, Is it a good solution at all?
cause this solution prints all the comments all over again each time the user presses submit.
Any suggestions?
I would appreciate your help.
This is My Code:
main.php
<html>
<head>
<title> </title>
<script language="Javascript" src="ajax.js"> </script>
</head>
<body>
<h1 align="center"><font color="#000080">Welcome, </font></h1>
<p align="center"><font color="#000080">Enter your name & comment then press
"Submit Button"</font></p>
<form name="f1" method="post">
<p align="center"><font color="#000080">
Enter your name: <input type="text" name="username" id="username">
<font color="#000080">
Enter your comment: <input type="text" name="comment" id="comment">
<input value="Submit" type="button"
onclick='JavaScript:postRequest()' name="showdate"></font></p>
</form>
</br></br>
<?php
include_once("config.php");
$query = "SELECT * FROM `comments` ORDER BY 'id'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center">';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
?>
<div id="result" align="center"> </div>
</body>
</html>
showcomments.php
name: ' .$name;
echo 'comment: ' .$content;
echo ''
?>
ajax.js
function postRequest() {
var xmlHttp;
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var usr=window.document.f1.username.value;
var cmnt=window.document.f1.comment.value;
var url = "showcomments.php?username=" + usr +"&comment=" + cmnt;
xmlHttp.open('GET', url, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange =function(){
if(xmlHttp.readyState == 4){
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(url);
}
function updatepage(str){
document.getElementById("result").innerHTML +=
"<font color='red' size='5'>" + str + "</font>";;
}
(P.S: I created a table using MySql named "comments" with the following columns: Id, Added_by, comment.)
I would not only print the name and comment in you PHP file, but also a form with a hidden field containing the ID. Or, even better, a button with a onClick="deleteComment(ID)". More importantly: place every comment in a p-tag with an ID, with id=comment-id. Your main.php PHP file would be expanded with this:
while($row = mysql_fetch_array($qry_result)){
echo ' <p align="center" id="'.$row['id'].'>';
echo "<font color='red' size='5'> name: </br>".$row['added_by'];
echo " </br>comment: </br>".$row['comment'];
echo "</font></p>";}
This (ajax)-function deleteComment(ID) then sends the ID of the comment to be deleted to another PHP-script. This deletes it from the database.
Now you have two options: you either delete the p-tag on the page by it's ID (this is very easy with jQuery with the function $('IDofP').empty(); ) or you reload all the comments.

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.

Categories