Get javascript active when posting php ajax result through javascript - php

I have this html form:
<form method="post">
<input type="radio" name="news" id="new" value="nuova" onchange="newstype(this.id);">Nuova News
<input type="radio" name="news" id="mod" value="modifica" onchange="newstype(this.id);">Modifica News
<select name="news" id="modifica" style="display:none" onchange="shownews(this.value)">
<?php
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or die("Impossibile connettersi");
$querylistanews = "SELECT * FROM NEWS ORDER BY id DESC";
$listanews = $connection->query($querylistanews);
print '<option>Seleziona una news...</option>';
while ($newsdamodificare = $listanews->fetch_object()) {
print '<option value="'.$newsdamodificare->id.'">'.$newsdamodificare->data." - ".$newsdamodificare->title.'</option>';
}
$listanews->close();
$connection->close;
?>
</select>
</form>
this javascript:
function newstype(param) {
if(param == 'new') {
document.getElementById('crea').style.display = 'inline';
document.getElementById('modifica').style.display = 'none';
document.getElementById('newsdamodificare').style.display = 'none';
} else {
if(param == 'mod') {
document.getElementById('crea').style.display = 'none';
document.getElementById('modifica').style.display = 'inline';
document.getElementById('newsdamodificare').style.display = 'inline';
}
}
}
function shownews(str) {
if (str=="") {
document.getElementById("newsdamodificare").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // codice per IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // codice per IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","modifica.php?news="+str,true);
xmlhttp.send();
}
and this php:
<head>
<script type="text/javascript" src="../editor/ckeditor.js"></script>
<script type="text/javascript" src="/js/charscounter.js"></script>
</head>
<?php
$news=$_GET["news"];
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or
die('Impossibile connettersi al database: ' . mysql_error());
$newsdaldatabase="SELECT * FROM NEWS WHERE id = '".$news."'";
$result = $connection->query($newsdaldatabase);
$count = mysqli_num_rows($result);
if($count==1){
while($dati = mysqli_fetch_array($result)) {
$id = $dati['id'];
$data = $dati['data'];
$title = $dati['title'];
$body = $dati['body'];
}
} else {
die('Errore del sistema. PiĆ¹ di una news selezionate: ' . mysql_error());
}
mysqli_close($connection);
?>
<div class="normal" id="modifica">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica news</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modificanews" method="post" action="italiano.php?modifica=yes">
<input name="idmodificanews" type="text" style="display:none" value="<?php echo $id ?>">
<input name="datanewsmodificata" type="text" maxlength="10" size="8" value="<?php echo $data ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="<?php echo $title ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
All is working quite well, except one thing:
when I select the news to edit, the content is from the server is correcly posted on the php, but on the HTML the scripts in the php (CKEDITOR and Char Cunter) are not active.
So, on my HTML, were the user will edit the news, i get only a simple textarea instead of the CKEDITOR, etc.
Is there a way to fix that? Can you help me somehow?
Thank you!
EDIT: I solved by myselft the problem. See solution as answer.

For those who have the same question:
I solved my problem in the following way: on javascript add a new row:
document.getElementById("newsdamodificare").action=CKEDITOR.replace('modificatesto');
between this 2 lines:
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
NEW LINE TO INSERT HERE
}
And remove from the php these rows:
<script>
CKEDITOR.replace('modificatesto');
</script>
Hope this helps!

You're trying to select your textarea by it's name, but CKEDITOR.replace('modificatesto'); is looking for an ID.
Try
<textarea id="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>

Related

Autofill Input Field Based On Another Input Field OnKeyUp (Dynamic Generated)

I hope today I'll find good solution for my case below.
Case
Actually, I have dynamic input fields and let say there field A, B and C. So, the purpose is when field A receives OnKeyUp Action then field B and C will autofill based query result from field A value.
index.php
<html>
<body>
<script type="text/javascript">
var ct = 1;
// Function Tambah Form
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// Link to Delete Form
var delLink = '<div style="text-align:left"><a id="del" href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// Function Delete Form
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
function ajaxFunction(str,divId)
{
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 stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById(divId).innerHTML=httpxml.responseText;
}
}
var url="cek.php";
url=url+"?txt="+str;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name="myForm">
<a id="new" href="javascript:new_link()">ADD NEW PAYMENT</a>
<div id="newlink">
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv');" name="username" /></td>
<td>
<div id="displayDiv">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<div id="newlinktpl" style="display:none" >
<div>
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv<?php echo ++$np;?>');" name="username" /></td>
<td>
<div id="displayDiv<?php echo $np;?>">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
cek.php
<?php
mssql_connect('localhost','sa','');
mssql_select_db('NCD');
$in=$_GET['txt'];
$msg="";
$t=mssql_query("SELECT * FROM DPaym1 WHERE (JENIS = 1) AND (DPSPAID = 0) AND (CNDPSNO = '$in')");
while($nt=mssql_fetch_array($t)){
//$msg = "$nt[CURRID]#$nt[AMOUNT]";
$curr = "$nt[CURRID]";
$amount = "$nt[AMOUNT]";
}
//echo $msg;
//echo "$curr $amount";
?>
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr" value="<?php echo $curr?>"></td>
<td><input type="text" name="amount" value="<?php echo $amount?>"></td>
</tr>
</table>
Above code already success for row 1. but when I input value in row 2 (dynamic add new row) the result change field B and C in row 1 not in row 2.

Submitting dynamic ajax field

I have an an ajax drop down box that if selected adds another field to a form, this works but this new field doesn't get submitted with the form. Any suggestions?
findTest.php called via ajax
<?php
$work = ($_GET['work']);
if ($work == "Work1") {
?>
<tr>
<td>New work1<input name="newWork1" size="20" type="text"/></td>
</tr> <?
} elseif ($work == "Work2") {
?>
<tr>
<td>New work<input name="newWork" size="20" type="text"/></td>
</tr><?
} elseif ($work == "Work3") {
?>
<tr>
<td>No work today</td>
</tr><?
}?>
Test.php
<?php
$page = '';
$answer = null; //clean start.
$Comments = $_POST['Comments'];
$new = $_POST['new'];
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message <?= $_POST['Comments'] ?>
and <?= $_POST['new'] ?> or this should be
work2 <?= $_POST['newWork'] ?></p>
<? } ?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
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 getWorkDone(workId) {
var strURL = "findTest.php?work=" + workId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML = req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right">Work Done:</td>
<td><select name="WorkDone" tabindex="14"
onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><p id="workdiv">New Work<input name="newWork" size="20"
type="text"/></td>
</tr>
<tr>
<td width="200" align="right">Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40"
rows="4"><?= $_POST[Comments] ?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit"
class="button" value="Submit">
</td>
</tr>
</tr>
</table></form>
UPDATE: new code.
findTest.php called via ajax
<?php
if (isset($_GET['work'])) {
$work= $_GET['work'];
if ($work == "Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
}?>
And Test.php
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
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 getWorkDone(workId) {
var strURL="findTest.php?work="+workId+"&new1="+"&$new";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML=req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right" >Work Done:</td>
<td><select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="">Select</option>
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr >
<td ></td>
<td ><p id="workdiv">New Work<input name="newWork" size="20" type="text" /></td>
</tr>
<tr>
<td width="200" align="right" >Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40" rows="4" ><?=$_POST[Comments]?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit" class="button" value="Submit">
</td>
</tr>
</tr>
</table>
</form>
UPDATE edit double up and correct $newWork to $newWork1
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";}
?>
This now shows n/a but not the value of newWork1
You have very modified the original question, I can only respond to what was previously.
The important part is also findTest.php
from this script you replace your
document.getElementById('workdiv').innerHTML=req.responseText;
So how does findTest.php know about $_POST['newwork1']
<td>New work1<input name="newWork1" ... value="<?=$_POST['newwork1']?>" /></td>..
This must come via a GET / POST, but in your GET there ist only
strURL="findTest.php?work="+workId;
Only 1 GET variable named $_GET['work'].
and you use this variable (without test)
$work=$_GET['work'];
And then you mixed the request from $_GET to $_POST['newwork1']
so why not use your select value to get it all together.
Test.php
...
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Noworktoday">No work today</option>
<option value="Other">Other</option>
</select>
...
findTest.php
if (isset($_GET['work'])) {
//for example : $work == "Work1"
$work=$_GET['work'];
if ($work=="Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
//<tr><td>New Work1<input name="newWork1" type="text" size="20" value="newWork1" /></td></tr>
Update:
You can not see your values because you did'nt echo them
and you have to test all $_POST
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a';
}
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a';
}
....
and so on for all possible values
echo your variables
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message = <? echo $Comments; ?>
and = <? echo $newWork1; ?> or this should be
work2 = <? echo $newWork; ?></p>
<? } ?>
Update:
I can not see the actual code, you need a if (isset ... for all possible variables . In my example I have described only two possibilities. You need also e.g.
if (isset($_POST['newWork2'])) { ...
if (isset($_POST['newOther'])) { ...
and so on !! And make only asimple output.
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
and put it logical together
This is illogical Work2 assigned to newWork !!!

Firefox does not submit my form

I have a php application that fetches the requests from mysql database and displays them for further approval. The form is fetched from send_req.php and is displayed inside the div on showrequests.php. This is the code for send_req.php
<table style="border:0;border-color:transparent">
<tr style="background-color:lightblue">
<td>Product ID</td>
<td>Name</td>
<td>Quantity</td>
<td><input type="checkbox" name="selectAll" /></td>
<td>Authorized Quantity</td>
</tr>
<form method="post" action="send_req.php">
<?php
$reqNum = $_POST['rId'];
echo "<h3>Request # $reqNum</h3>";
$showReqs = mysql_query("Select * from request where request_number='".$reqNum."' and status=0");
while($resultA = mysql_fetch_array($showReqs))
{
$rBy = $resultA['requested_by'];
$rTime = $resultA['request_time'];
$rId = $resultA['id'];
$pId = $resultA['product_id'];
$getPrName = mysql_query("select name from products where id='$pId'");
$prN = mysql_fetch_array($getPrName);
$prName = $prN['name'];
$rQuantity = $resultA['requested_quantity'];
$status = $resultA['status'];
?>
<tr>
<input type="hidden" name="rId[]" value="<?php echo $rId; ?>"/>
<td style="background-color:orange"><input type="text" name="prId[]" value="<?php echo $pId; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="prName[]" value="<?php echo $prName; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="quantity[]" value="<?php echo $rQuantity; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"></td>
<td><input type="text" name="pQuantity[]" /></td>
</tr>
<?php }
?>
<tr>
<td></td>
<td></td>
<td></td>
<input type="hidden" name="rNum" value="<?php echo $reqNum; ?>" />
<td></td>
<td><input type="submit" name="submitReq" value="Send" id="submit_req" style="backgroundColor:Transparent;border:0;color:blue;width:100;"/></td>
</tr>
</form>
</table>
<?php
echo "Requested By:$rBy at ".substr($rTime,11,18)." ".substr($rTime,0,10);
?>
This is the showrequests.php page
<html>
<head>
<script type="text/javascript">
function getRequest(ob)
{
var id = ob.id;
if(window.XMLHttpRequest)
{
ajaxOb = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
ajaxOb = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxOb.open("POST", "send_req.php");
ajaxOb.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxOb.send("rId=" + id);
ajaxOb.onreadystatechange = function()
{
if(ajaxOb.readyState == 4)
{
if(ajaxOb.status == 200)
{
document.getElementById("showTable").innerHTML = ajaxOb.responseText;
}
}
}
}
</script>
</head>
<body>
<?php
$mysql_con = mysql_connect("localhost","root","") or die("Could not connect ".mysql_error());
$mysql_db = mysql_select_db("cart",$mysql_con) or die("Unable to select db ".mysql_error());
echo "<h2 align='center'>Pending Requests</h2>";
$showReq = mysql_query("Select distinct(request_number) as rNums from request where status=0");
?>
<div style="float:left;margin-right:15px;">
<br/>
<?php
while($result = mysql_fetch_array($showReq))
{
$rNum = $result['rNums'];
?>
<input type="button" name="fetchReq" id="<?php echo $rNum; ?>" value="<?php echo "Request # $rNum"; ?>" style="margin-bottom:5px;backgroundColor:Transparent;border:0;color:blue;width:100;text-Decoration:underline" onclick="getRequest(this)"/>
<?php
echo "<br/>";
}
?>
</div>
<div id="showTable" style="float: left">
</div>
</body>
</html>
My problem now is that everything works fine in chrome and IE but the form is not submitted when i click the submit button in firefox. I am using firefox 20.0.1. Update: I have removed the html,head and body tags from send_req.php
still not working
form is not allowed inside table. Please see also
Form inside a table
Regards,
Michael
Reminder : the structure of an HTML document is :
<!-- No div before html tag -->
<!DOCTYPE html> <!-- Doctype for HTML5 ; use whatever doctype you need -->
<html>
<head>
</head>
<!-- No div before body tag -->
<body>
<!-- Divs only belongs here -->
</body>
</html>
<!-- No div after html tag -->
If you don't follow this basic structure, you're forcing the browser to interpret your invalid code (+ quirks mode when you don't provide a doctype).
Some browser guess well what you tried to do, others don't, as Firefox might.
Please use a HTML validator as W3's validator to check your syntax.

Validate Dynamic Dropdown With Ajax

I have a drop down menu of mobile brands. When a user selects a mobile brand a dynamic drop populates with the mobile model according to the mobile brand I want to validate that mobile model drop down for a blank select value. I am using ajax xmlhttp request for getting the mobile model drop down menu.
My entire code is:
Code for page with mobile brand drop down menu
<script type="text/javascript">
function validate() {
if (document.myform.step3_mobilebrand.value=="") {
document.getElementById("error1").innerHTML = (error1) ? "<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilebrand.focus();
return false;
}
var myTextField = document.myform.getElementById('step3_mobilemodel').value;
if (myTextField == "") {
document.getElementById("error2").innerHTML = (error2)?"<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilemodel.focus();
return false;
}
}
</script>
<?php
if (isset($_POST['submitted']) and $_POST['submitted']=="Continue") {
$mobilebrand1 = $_POST['step3_mobilebrand'];
$mobilemodel1 = $_POST['step3_mobilemodel'];
if ($mobilemodel1=="") {
echo "Please Select Mobile Model";
}
$connectiontype=$_POST['step3_connectiontype'];
$internet=$_POST['step3_internet'];
include("admin/config.php");
$sql="insert into member_detail (mobilebrand,mobilemodel,connection_type,internet) values('$mobilebrand1','$mobilemodel1','$connectiontype','$internet')";
mysql_query($sql);
}
?>
<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>
<form name="myform" method="post" action="" onsubmit="return validate();">
<table>
<tr>
<td>Mobile Brand</td>
<td><?php
include ("admin/config.php");
echo "<select name='step3_mobilebrand' onchange='showUser(this.value)'><option value='' selected>Select Mobile Brand</option>";
$result = mysql_query ("select * from mobilebrand order by mobilebrand");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['id']."\">".htmlspecialchars($adcom['mobilebrand'])."</option>";
}
echo "</select>";?><span id="error1" style="color:red;"></span></td>
</tr>
</table>
<div id="txtHint"></div>
<table>
<tr>
<td>Connection Type</td>
<td><input type="radio" name="step3_connectiontype" value="PrePaid" checked="checked">Prepaid
<input type="radio" name="step3_connectiontype" value="PostPaid">Postpaid
<span id="error3" style="color:red;"></span>
</td>
</tr>
<tr>
<td>Have Internet On Mobile</td>
<td><input type="radio" name="step3_internet" value="Yes" checked="checked">Yes
<input type="radio" name="step3_internet" value="No">No
<span id="error4" style="color:red;"></span>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitted" value="Continue"></td>
</tr>
</table>
</form>
and the code of getuser.php is
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
include("admin/config.php");
echo "<select name='step3_mobilemodel' id='step3_mobilemodel' ><option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}
echo "</select>"; ?>
</td>
</tr>
</table>
The Output am getting is correct i just want to validate the mobile model drop down menu for blank select
For validating select you can do:
var e = document.getElementById("step3_mobilemodel");
var mobileVal = e.options[e.selectedIndex].value;
if(mobileVal == "") {
...//show your error here
}
Hope it helps
This is pretty much what Sudhir posted (+1 from me) but with an example in a fiddle: http://jsfiddle.net/5TYwH/1/ using the onchange event handler.
May be you can just add a php validation for $q.
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
echo "<select name='step3_mobilemodel' id='step3_mobilemodel'>"
if($q != ""){
include("admin/config.php");
echo "<option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}}else{ echo "<option value=''>Please select a mobile first</option>";} echo "</select>";?></td>
</tr></table>

Getting values depending on the dropdown

I have a dropdown list for items. What I want to do is get the item quantity, remaining quantity and dispatched item values which depends on the value in the drop down.
I have this code :
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " . mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><?php
$row = mysql_fetch_object($itemresult);
echo $row->item_quantity; ?></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><?php echo $row->rem_quantity; ?></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><?php echo $row->stocks_dispatched; ?></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
I really don't know how to start the code because i'm new to this approach. If you can help me it's much appreciated. Thanks in advance.
This works: The jist is that the page uses ajax to call a script, which will deliver XML of the values you need, and will then populate those fields accordingly. :
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script>
function updateFields(itemname){
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)
{
var xmlDoc=xmlhttp.responseXML;
var iQdata=xmlDoc.documentElement.getElementsByTagName("ITEMQUANTITY");
var rQdata=xmlDoc.documentElement.getElementsByTagName("REMAININGQUANTITY");
var sDdata=xmlDoc.documentElement.getElementsByTagName("STOCKSDISPATCHED");
var iQ=iQdata[0].firstChild.nodeValue;
var rQ=rQdata[0].firstChild.nodeValue;
var sD=sDdata[0].firstChild.nodeValue;
document.getElementById("itemQuantity").innerHTML=iQ;
document.getElementById("remainingQuantity").innerHTML=rQ;
document.getElementById("stocksDispatched").innerHTML=sD;
}
}
xmlhttp.open("GET","quantity_script.php?itemname="+itemname,true);
xmlhttp.send();
}
</script>
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname" onchange="updateFields(this.value)">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " .mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><div id="itemQuantity"></div></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><div id="remainingQuantity"></div></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><div id="stocksDispatched"></div></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
</body>
</html>
And then you'd also make a script on your site "quantity_script.php" that would be something like the following:
<?php
//include your DB connection info
$itemname=mysql_real_escape_string($_POST["itemname"]);
$item="SELECT ".$itemname." FROM stocks";
$itemresult = mysql_query($item);
$row=mysql_fetch_assoc($itemresult);
header('Content-type: text/xml');
echo "<ROOT>";
echo "<ITEMQUANTITY>".$row["item_quantity"]."</ITEMQUANTITY>";
echo "<REMAININGQUANTITY>".$row["rem_quantity"]."</REMAININGQUANTITY>";
echo "<STOCKSDISPATCHED>".$row["stocks_dispatched"]."</STOCKSDISPATCHED>";
echo "</ROOT>";
?>

Categories