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" :)
Related
Below is my code.
Firstly, run the index.php Then there is a dropdown list will display and need to select a value from the dropdown. so far, dropdown will display value 1 or 2. If you select 2 it will display the value that has been selected together with the "date" field called from the display-date.php and from the "date" field, you may choose the date from calendar which called using datepicker plugin.
Now.. the problem is...I had select the date from calendar but the date selected didn't appear in the date input field. where am I wrong?
Hope anyone could help me please... :)
Thanks.
Here is index.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<script>
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}
else {
// IE5/IE6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("results").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-date.php?q="+str, true);
xhr.send(null);
}
}
</script>
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.value)">';
echo '<option value="None">-- Select Option --</option>';
echo '<option value="1">One</option>';
echo '<option value="2">Two</option>';
echo '</select>';
?>
</div>
<br/><br/>
<p>You selected: <span id="results"></span></p>
</body>
</html>
Here is display-date.php
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<html>
<head>
<style>
#date_input{
text-indent: -500px;
height:25px;
width:200px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
</body>
</html>
<?php
}
?>
Modify the display-date.php . Html base structure is no longer needed.
<?php
$Q = $_GET["q"];
echo $Q;
?>
<?php
if ($Q == '2'){
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="dd-M-yy" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
<script type="text/javascript">
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px",
top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" :
($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
</script>
<?php
}
?>
There is no need to use ajax in your case, Ajax must not be used the way you showed in your question.
Ajax not used to draw html in DOM
No need to use ActiveXObject , It is insecure and I don't think we should support IE 5 or IE 6 anyways in modern development.
If you need to use ajax, Use JQuery's ajax function instead of XMLHttpRequest, As i see you are already using it.
Here is the code which works without ajax and works as it should be.
function getData(str){
$('.showInput').hide();
$('.showText').text('');
if(str != ""){
str = parseInt($.trim(str));
if(str == 2){
$('.showInput').show();
}else{
$('.showText').text(str);
}
}
}
$(document).ready(function(){
$("#date_input").datepicker({ dateFormat: 'dd-M-yy' });
});
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
</head>
<body>
<style>
.showInput{
display:none;
}
</style>
<div>
<select title="Select one" name="selectcat" onChange="getData(this.value)">
<option value="">-- Select Option --</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<br/><br/>
<p>You selected: <span id="results">
<span class="showText"></span>
<span class="showInput">
<input id="date_input" dateformat="dd-M-yy" type="text"/>
</span>
</p>
</body>
</html>
I've found 5-6 similar questions on StackOverflow, but I wasn't able to see the correlation to my code — theirs seems to be a different approach — so I wasn't able to squeeze a solution out of them.
Essentially, when I call up my report.html page, and enter in valid dates, like 2015-06-01 and 2015-06-12, choose Deal "A" and hit Submit ... a table of results briefly appears in the target div at the bottom ... then promptly disappears.
An additional strange thing, is when I hit the back button on the browser, there's my result (and it stays put)!
One other thing: If I add action="ajaxFunction()" to the , the results show up and stay (although I also get a nice big jQuery Mobile error message box in the middle of my screen for a few seconds).
Anyway, I think I'm CLOSE. Code below. Thanks!
report.html
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<title> Report</title>
<link rel="stylesheet" href="css/style_report.css" type="text/css">
<link rel="stylesheet" href="../../../jquery-mobile/demos/css/themes/default/jquery.mobile-1.4.5.min.css">
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="panel" id="myPanel">
<form name="sqlForm" method="" action="" id="sqlForm" >
<div class="date-range">
<p>Choose a date range</p>
<div><input type="text" id="startDate" name="startDate" data-role="date" data-date-format="yy-mm-dd"></div>
<p>to</p>
<div><input type="text" id="endDate" name="endDate" data-role="date" data-date-format="yy-mm-dd"></div>
</div>
<div class="deal_type">
<p>Choose one or more deals</p>
<select name="dealCode" id="dealCode">
<option value="*">Select a deal</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
<option value="H">H</option>
<option value="I">I</option>
<option value="J">J</option>
<option value="K">K</option>
<option value="L">L</option>
<option value="M">M</option>
<option value="N">N</option>
<option value="O">O</option>
</select>
</div>
<input data-rel="close" type="submit" id="submit" value="Submit" onclick="ajaxFunction()" value="Query MySQL" >
</form>
<!-- BUTTON HERE TO GO TO RESULTS AND CLOSE PANEL -->
</div><!-- PANEL ENDS -->
<div class="wrapper">
<h1>REPORTS</h1>
<div data-role="main" class="ui-content">
<!-- PANEL BUTTON -->
<a href="#myPanel" class="ui-btn ui-shadow ui-corner-all ui-btn-inline ui-btn-icon-left ui-icon-bars">
Filter results</a>
<div id="sqlTable" style="background-color:yellow; height:auto;">Person info will be listed here...</div>
</div>
</div>
</div>
<script src="../../../jquery-mobile/demos/js/jquery.js"></script>
<script src="../../../jquery-mobile/demos/js/jquery.mobile-1.4.5.min.js"></script>
<script src="http://cdn.rawgit.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
<!-- JQuery datepicker -->
<!--Datepicker relevant external files-->
<script src="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.js"></script>
<script src="https://rawgithub.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
<link rel="stylesheet" href="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.css">
<!-- SCRIPT TO SET UP THE DATEPICKER CORRECTLY -->
<script>
$(document).ready(function () {
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(document).on("click", "#date1", function () {
var viewportwidth = $(window).width();
var datepickerwidth = $("#ui-datepicker-div").width();
var leftpos = (viewportwidth - datepickerwidth) / 2;
$("#ui-datepicker-div").css({
left: leftpos,
position: 'absolute'
});
});
$("#date1").datepicker({
onSelect: function () {
alert("HAHA");
}
});
}
);
</script>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('sqlTable');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startDate = document.getElementById('startDate').value;
var endDate = document.getElementById('endDate').value;
var dealCode = document.getElementById('dealCode').value;
var queryString = "?startDate=" + startDate + "&endDate=" + endDate + "&dealCode=" + dealCode;
ajaxRequest.open("GET", "getReport.php" + queryString, true);
ajaxRequest.send(null);
}
console.log("ffff", "startDate="+str1+"&endDate="+str2+"&dealCode="+str3);
</script>
</body>
</html>
getReport.php
<?php
// MAKE THE MAIN CONNECTION, AND GIVE IT A NAME, 'CON'
$con = mysqli_connect("URL", "USERNAME", "PASSWORD", "DB");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
// THE INFO AFTER THE COMMA, "MAIN_REPORT", APPEARS TO BE USELESS, BUT HAS TO BE THERE.
mysqli_select_db($con,"MAIN_REPORT");
//GRAB THE STUFF FROM THE HTML FORMS
$startDate = $_REQUEST['startDate'];
$endDate = $_REQUEST['endDate'];
$dealCode = $_REQUEST['dealCode'];
// MAKE YOUR OVERALL QUERY HERE.
$sql="SELECT * FROM `oasis_bagels` WHERE `dealDate` > '$startDate' AND `dealDate` < '$endDate' ORDER BY `dealDate`";
$result = mysqli_query($con,$sql);
// THIS TESTS YOUR QUERY, OFTEN GIVING YOU A HELPFUL ERROR MESSAGE
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
?>
<?php /*?> $all = mysqli_query(
$con,
//"SEL
SELECT * FROM `oasis_bagels` WHERE `dealCode` = ' "$q" ';
// SELECT * FROM `oasis_bagels` WHERE `dealDate` > '$startDate' AND `dealDate` < '$endDate'
// SELECT * FROM `oasis_bagels` WHERE `dealDate` > '2015-01-01' AND `dealDate` < '2100-01-01'
// WHERE dealCode=*"
);
<?php */?>
<!-- ////////////////////////////////////////////////////////// -->
<!-- THE CODE BELOW GIVES ME THE DATE AND TIME RESULTS I WANT.
NONE OF THIS SHOULD CHANGE, AS IT'S ONLY FORMATTING THE RESULTS. -->
<!-- ////////////////////////////////////////////////////////// -->
<table border="1" cellpadding="4" cellspacing="4" bordercolor="#CFCBCB">
<tr class="header">
<th>Purchased</th>
<th>Code</th>
<th>Name</th>
<th>Value</th>
</tr>
<?php while ($row = mysqli_fetch_array($result)): ?>
<?php $date = $row['dealDate']; ?>
<?php $code = $row['dealCode']; ?>
<?php $name = $row['dealName']; ?>
<?php $value = $row['dealValue']; ?>
<tr>
<td>
<span class="date">
<?php
$PhpDate = strtotime($date);
$FormattedPhpDate = date('m/d/y', $PhpDate );
echo $FormattedPhpDate;
?></span><br>
<span class="time"><?php
$PhpDate = strtotime($date);
$FormattedPhpDate = date('(g:i A)', $PhpDate );
echo $FormattedPhpDate;
?></span>
</td>
<td class="code"><?php echo $code; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php endwhile; ?>
</table>
<?php mysqli_close($con); ?>
change your submit button to ...
<button type="button" data-rel="close" id="submit" value="Query MySQL" >
<input style="display: none;" type="submit" id="realsubmit">
and add this ...
$("#submit").on('click', function() {
// do some stuff
$("#realsubmit").trigger('click');
return false;
});
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.
I'm working on a simple HTML form that either detects if a record exists (in an XML file) and populates all the fields OR detects that the form doesn't exist and on submit, creates the record (or modifies the current one if it's been modified)
I'm working on the part now that would add a non existing record and/or modify an existing one.
The AJAX calls a PHP file, and in the PHP file I'd like to check if the record exists or not and perform the appropriate operations accordingly. I would like the user of the form to be informed (no pun intended) of what operation was carried out (i.e. "Added the Record" or "Modified the Record").
To start with, all I have my PHP doing right now is returning the text added. I want to see if I can get "Added the Record" to properly display in original HTML file.
EXPECTED: When I click Submit, I expect the message "Added the Record" or "Modified the Record" to appear under the form, depending on the return from the PHP file.
THE ERROR: Now, when I click Submit, the form resets itself, adds all the parameters to the URL and I don't get any message from the AJAX request.
Here's my code:
HTML Page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<script type="text/javaScript">
function checkID(val){
if (val.value.length != 6) //Since student ID's are six digits
return;
//inID = val.value;
//if (inID.length < 6) return;
xhr = new XMLHttpRequest();
xhr.open('GET', 'processor.php?studentID=' + document.forms[0].elements[0].value);
xhr.onreadystatechange = function() {
/**
if (xhr.readystate != 4 || xhr.status != 200){
document.getElementById("status").innerHTML = "<p> Not Done Yet</p>";
}
**/
if (xhr.readyState === 4 && xhr.status === 200){
document.getElementById("status").innerHTML = "";
parse(xhr.responseXML);
}
}
xhr.send();
document.getElementById("status").innerHTML = "<p> Not Done Yet</p>";
}
function parse(xml){
if (xml == null) alert("Null!");
var student = xml.getElementsByTagName('student');
if (student.length == 0) alert("No Student's Found with that ID");
var content = student.item('0');
var name = content.getElementsByTagName('fullname');
name = name.item(0).childNodes[0].nodeValue;
document.forms[0].elements[1].value = name;
var phone = content.getElementsByTagName('phone');
phone = phone.item(0).childNodes[0].nodeValue;
document.forms[0].elements[2].value = phone;
var email = content.getElementsByTagName('email');
email = email.item(0).childNodes[0].nodeValue;
document.forms[0].elements[3].value = email;
}
function addOrModify(curr){
xhr2 = new XHRHttpRequest();
xhr2.open('GET', 'addOrModify.php'); //?studentID=' + document.forms[0].elements[0].value);
xhr2.onreadystatechange = function(){
if (xhr2.readyState === 4 && xhr2.status === 200){
if (xhr.responseText == "added") {document.getElementById("status").innerHTML = "<p>Added the Record</p>"};
}
}
xhr.send();
return false;
}
</script>
<style type="text/css">
#container {
margin: 0 auto;
padding: 30px;
text-align: center;
}
.centerp {
font-size: 150%;
text-align: center;
}
table {
align: center;
}
</style>
<title>Student Profile</title>
</head>
<body>
<p class="centerp"> Student Profiles </p>
<div id="container">
<form>
<table align="center">
<label>
<tr>
<td>Student ID</td>
<td><input type="text" name="studentID" onblur="checkID(this)"> </input></label></td>
</tr>
</label>
<label>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"> </input></label></td>
</tr>
</label>
<label>
<tr>
<td>Phone</td>
<td><input type="text" name="phone"> </input></label></td>
</tr>
</label>
<label>
<tr>
<td>Email</td>
<td><input type="text" name="email"> </input></label></td>
</tr>
</label>
<tr>
<td> <input type="submit" onclick="return addOrModify()"> </input></td></tr> </td>
</tr>
<tr>
<td> <div id="status">
</div> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
Simple PHP page:
<?php
aOm();
function aOm(){
header("Content-type: text/plain; charset=utf-8");
echo "added";
}
?>
minor typos in your code
function addOrModify(curr){
xhr2 = new XMLHttpRequest(); // xhr2 = new XHRHttpRequest();
xhr2.open('GET', 'addOrModify.php'); //?studentID=' + document.forms[0].elements[0].value);
xhr2.onreadystatechange = function(){
if (xhr2.readyState === 4 && xhr2.status === 200){
if (xhr2.responseText == "added") // if (xhr.responseText == "added")
{document.getElementById("status").innerHTML = "<p>Added the Record</p>"};
}
}
xhr2.send(); //xhr.send();
return false;
}
that should get it working. No mistakes in your php code though
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.