I have read a little about hoisting, but I am not sure how it applies in this situation. I have a select value that is shown and hidden dynamically and the value of this select element is always undefined. Please help! Thanks
HTML
<tr>
<td>Type:</td>
<td>
<select id="type" onchange="rulesShown()">
<option value="ATC">ATC</option>
<option value="PILOT">PILOT</option>
<select>
</td>
</tr>
<tr id="rules">
<td>Rules:</td>
<td>
<select id="rules">
<option value="FAA">FAA</option>
<option value="ICAO">ICAO</option>
<select>
</td>
</tr>
Javascript:
<script>
function rulesShown() {
if(document.getElementById("type").value=="ATC"){
document.getElementById("rules").style.display = "";
document.getElementById("rules").style.removeProperty( 'display' );
}
else{
document.getElementById("rules").style.display = "none";
}
}
function verifyData() {
var email1 = document.getElementById("email1");
var email2 = document.getElementById("email2");
var comments = document.getElementById("comments").value;
if(comments!=""){
if(email2==null){
//submit form
submit();
}
else if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email1.value)){
if(email1.value == email2.value) {
//submit form
submit();
}
else {
//emails dont match
alert('Email addresses do not match!');
}
}
else{
//invalid email address
alert('Please enter a valid email address!');
}
}
else{
alert('Please enter some comments!');
}
}
function submit(){
var vid = <?php echo $user['vid'] ?>;
var email = document.getElementById("email1").value;
var type = document.getElementById("type").value;
var rules = document.getElementById("rules").value;
var comments = document.getElementById("comments").value;
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("page").innerHTML = xhttp.responseText;
}
}
xhttp.open("POST", "/content/training/request/submit.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("vid="+vid+"&email="+email+"&type="+type+"&rules="+rules+"&comments="+comments);
}
</script>
No need for the file the AJAX is calling. It simply POST's the 'rules'. As far as I can tell this is a javascript hoisting problem, but I don't know why. Thanks
This has nothing to do with hoisting which is pure javascript concept. You have two elements with same id. A <tr> and a <select>. Which is forbidden by html. One of the implications of this is that browser doesn't guarantee which element will be returned by getElementById()
Related
I'm stuck..I have made a system which gets all colleges from a specific subject, and I want javascript to select the college the user has selected when he clicks on one so the presence of that class can be shown, just a summary: the user selects a subject, an AJAX request gets all colleges from that subject and another AJAX request has to get that specific college and use it to display the data.
This specific function gets the data from the subjects and displays them in a div with the id 'colleges'
function showAanwezigheid(str) {
if (str == "") {
document.getElementById("colleges").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("colleges").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../controller/docentController.php?action=getColleges&vak="+str,true);
xmlhttp.send();
}
}
Here is the controller which calls the query and displays the result:
$vak = $_GET['vak'];
$colleges = $q->getColleges($vak);
echo "<select id='college'>";
echo "<option>Selecteer een college:</option>";
foreach($colleges as $college){
echo "<option value='".$college->getCollege()."'>College ".$college->getCollege()."</option>";
}
echo "</select>";
}
This is the id where the result is being displayed
<span id="colleges"></span>
And this function should select the 'select' tag with the id 'college' to get that value on change
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = this.value;
alert(vak);
$('#college').on('change', function() {
var college = this.value;
alert(college);
});
});
});
I feel like there would be such an easy fix but I just can't seen to make it work...
Change jQuery code like below:-
$(document).on('change','#vak',function() {
var vak = $(this).val();
alert(vak);
});
$(document).on('change','#college',function() {
var college = $(this).val();
alert(college);
});
Note:- Make sure that jQuery library added before your script code. Otherwise you will get $ is undefined error
This is called Event Delegation
IF you want to get the value of the #college select on change then this would be simpler:
$(document).ready(function(){
$('#vak').on('change', function() {
var vak = $(this).val();
alert(vak);
});
$('#college').on('change', function() {
var college = $(this).val();
alert(college);
});
});
IF you noticed, The onchange of the #vak and the #college is separated
I have been trying to create some select inputs that depend on the previous input in an html form using HTML Javascript PHP and MYSQL. This has worked with one of my previous pages, and so when creating this new one I just defined a new function in the javascript file and created a new php file to send data to as I wanted to output something different for the last select box in the form.
Even though I mirrored the previous function and php file changing only a few minor details, I am not able to see any of my created options for the last dropdown select and I dont seem to be getting any errors practically a blank php page with no errors is getting passed through, and I am not sure why this is happening.
Here is a screenshot of my form and you can see the 'Rack Unit Location' option does not create any options and is blank yeth the other select boxes work fine:
Form Screenshot
This is the section of my HTML form, so I want Rack Unit Location to depend on Rack Number, which depends on Location and in turn depends on Rack.
<tr>
<th>Rack </th>
<script src='includes/Jquery/default.js'></script> <!-- Link to new Javascript file -->
<td>
<select id='rack_name' name="rack_name" onchange="window.loadLocation()">
<option disabled="disabled" selected="selected">Rack Name</option>
<?php
$r = mysqli_query($conn, "SHOW TABLES WHERE Tables_in_network Like 'rack%'");
while($row=mysqli_fetch_assoc($r)){
echo "<option value=".$row['Tables_in_network'].">".$row['Tables_in_network']."</option>";
}
?>
<option value="no_rack">Not in Rack</option>
</select>
</td>
</tr>
<tr>
<th>Location</th>
<td>
<select id="location" name="location" onchange="window.selectrack()">
<option disabled="disabled" selected="selected">Location</option>
</select>
</td>
</tr>
<tr>
<th>Rack Number</th>
<td>
<select id="rackno" name="rackno" onchange="window.selectpduunit()">
<option disabled="disabled" selected="selected">Rack Number</option>
</select>
</td>
</tr>
<tr>
<th>Rack Unit Location</th>
<td>
<select name="rackunit" id="rackunits">
<option disabled="disabled" selected="selected">Rack Unit Number</option>
</select>
</td>
</tr>
Those onchange functions are defined in the following Javascript file:
function loadLocation(){
var formName = 'switch';
var rackname = document[formName]['rack_name'].value;
var xmlhttp = null;
if(typeof XMLHttpRequest != 'udefined'){
xmlhttp = new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}else{
throw new Error('You browser doesn\'t support ajax');
}
xmlhttp.open('GET', 'load_location.php?rack='+rackname, true);
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4)
window.insertLocation(xmlhttp);
};
xmlhttp.send(null);
}
function insertLocation(xhr){
if(xhr.status == 200){
document.getElementById('location').innerHTML = xhr.responseText;
}else{
throw new Error('Server has encountered an error\n'+'Error code = '+xhr.status);
}
}
function selectrack(){
var formName = 'switch';
var rackname = document[formName]['rack_name'].value;
var location = document[formName]['location'].value;
var xmlhttp = null;
if(typeof XMLHttpRequest != 'undefined'){
xmlhttp = new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}else {
throw new Error('You browser doesn\'t support ajax');
}
xmlhttp.open('GET', 'select_rack_number.php?location='+location+'& rack='+rackname, true);
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4)
window.insertrackno(xmlhttp);
};
xmlhttp.send(null);
}
function insertrackno(xhr){
if(xhr.status == 200){
document.getElementById('rackno').innerHTML = xhr.responseText;
}else{
throw new Error('Server has encountered an error\n'+'Error code = '+xhr.status);
}
}
function selectrackunit(){
var formName = 'switch';
var rackname = document[formName]['rack_name'].value;
var location = document[formName]['location'].value;
var rackno = document[formName]['rackno'].value;
var xmlhttp = null;
if(typeof XMLHttpRequest != 'udefined'){
xmlhttp = new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}else{
throw new Error('You browser doesn\'t support ajax');
}
xmlhttp.open('GET', 'select_rack_unit.php?location='+location+'&rack='+rackname+'&rackno='+rackno, true);
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4)
window.insertrackunit(xmlhttp);
};
xmlhttp.send(null);
}
function selectpduunit(){
var formName = 'switch';
var rackname = document[formName]['rack_name'].value;
var location = document[formName]['location'].value;
var rackno = document[formName]['rackno'].value;
var xmlhttp = null;
if(typeof XMLHttpRequest != 'udefined'){
xmlhttp = new XMLHttpRequest();
}else if(typeof ActiveXObject != 'undefined'){
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}else{
throw new Error('You browser doesn\'t support ajax');
}
xmlhttp.open('GET', 'select_pdu_unit.php?location='+location+'&rack='+rackname+'&rackno='+rackno, true);
xmlhttp.onreadystatechange = function (){
if(xmlhttp.readyState == 4)
window.insertpduunit(xmlhttp);
};
xmlhttp.send(null);
}
function insertrackunit(xhr){
if(xhr.status == 200){
document.getElementById('rackunits').innerHTML = xhr.responseText;
}else{
throw new Error('Server has encountered an error\n'+'Error code = '+xhr.status);
}
}
function insertpduunit(xhr){
if(xhr.status == 200){
document.getElementById('rackunits').innerHTML = xhr.responseText;
}else{
throw new Error('Server has encountered an error\n'+'Error code = '+xhr.status);
}
}
And here is the code in the php file that doesn not seem to be working for the selectpduunit function:
<?php
require 'includes/opendb.php';
if(isset($_GET['location']) && ($_GET['rack']) && ($_GET['rackno']) )
{
$b = $_GET['location'];
$e = $_GET['rack'];
$d = $_GET['rackno'];
$first_unit='1';
$explode=explode('-',$e);
$last_unit=$explode[1];
var_dump($b);
var_dump($e);
var_dump($d);
var_dump($explode);
while($first_unit<='4'){ //While Loop creates port columns in new table for each port on PDU.
if('10' > $count){
$column [] = '`PDU-0'.$first_unit.'`,'; //Storing port number as string in array."`port-0".$count."` varchar (255) NOT NULL";
}else{
$column [] = '`'.'PDU-'.$first_unit.'`'.',';
}
++$first_unit;
}
$empty = '';
foreach($column as $c){
$empty = $empty.$c;
}
//$empty = rtrim($empty2, ",");
$select="SELECT $empty FROM `$e` WHERE location = '$b' AND `Rack-Number` = '$d'";
var_dump($select); // Outputs the above generated MySQL string
if(!mysqli_query($conn,$select)){
die("Error".mysqli_error($conn));
}else{
$r = mysqli_query($conn,$select);
}
$unit_1 = '1';
while ('4' >= $unit_1){
if($unit_1 <'10'){
$column1[] ='PDU-'.'0'.$unit_1;
} else{
$column1[] ='PDU-'.$unit_1;
}
++$unit_1;
}
//var_dump($column1); // Outputs the above generated strings. The string should be column names.
$rackunit ='';
while($row = mysqli_fetch_assoc($r)) {
if($e == 'no_rack' || $e == 'vm_rack'){
//$rackunit =$rackunit.'<option value="'.$row["Unit"].','."Unit".'">'.'('."Unit".')'.' '.$row["Unit"].'</option>';
echo "fail";
}else{
foreach($column1 as $c1){
$rackunit =$rackunit.'<option value="'.$row["$c1"].','.$c1.'">'.'('.$c1.')'.' '.$row["$c1"].'</option>';
}
}
}
var_dump($rackunit);
if($rackunit == '')
echo 'An Error has occurred. Dropdown Menu is not being populated.';
else
?>
<select name="rackunit" id="rackunit">
<option disabled="disabled" selected="selected">Rack Unit Number</option>
<?php echo $rackunit ?>
<option value="1">Test</option>
</select>
<?php
}
?>
Any idea what the issue is?
There is a typo in your code. In method selectpduunit as well as selectrackunit
if(typeof XMLHttpRequest != 'udefined'){
It should be instead
if(typeof XMLHttpRequest != 'undefined'){
May be because of that you are not able to create a new XMLHttpRequest object. Give it a try.
I have a php page which I want to give me dynamically result from the drop down list I am choosing. The detail regarding the choosed option is saved in the database. So, basically to get the detail from the DB dynamically when I choose an option.
First Page from where I am selecting the data (Here the data is events)
<form name="ParticularFest" action="" method="post">
<table align="center">
<tr>
<tr><td><br/></td></tr>
<td><h4>Fest Name: </h4></td>
<td>
<select name="EventId" id="EventId" onchange="javascript: return ParticularValidate();"><option>Select Event</option>
<?php
$sql="Select EventName,MEventId from Tbl_Main where Status=0 and CategoryId=1";
$stmnt=sqlsrv_query($conn,$sql);
while( $row = sqlsrv_fetch_array( $stmnt,SQLSRV_FETCH_BOTH))
{
echo'<option value="'.$row["MEventId"].'">'.$row["EventName"].'</option>';
}
?>
</select>
</td>
</tr>
</table>
<div id="display"></div>
</form>
<script type="text/javascript">
function ParticularValidate() {
var errorMessage = null;
var MEventId = document.ParticularFest.EventId.value
var status = null;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
//alert("firefox");
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
status = xmlhttp.responseText;
document.ParticularFest.display.innerHTML = status;
}
}
xmlhttp.open("GET", "ParticularValidate.php?MEventId=" + MEventId, true);
xmlhttp.send();
}
</script>
The next page is the one to which I am redirecting, i.e. the ParticularValidate.php
<?php
include_once("Db.php");
$MEID=$_REQUEST['EventID'];
$obj=new Db;
?>
<table align="center">
<tr>
<th width="200" align="center"><br/><h3><b>Program Name</b></h3></th>
<th width="340" align="center"><br/><h3><b>Name</b></h3></th>
<th width="200" align="center"><br/><h3><b>Mobile No.</b></h3></th>
<th width="200" align="center"><br/><h3><b>Email</b></h3></th>
<th width="200" align="center"><br/><h3><b>College Name</b></h3></th>
<tr><td><br></td></tr>
</tr>
<?php
$sql="select distinct na.ProgramName,ma.Name,ma.Mob,ma.Email,ma.CName from Tbl_Main as sa inner join Tbl_UserProgram as ra on sa.MEventId=ra.EventId inner join Tbl_UserReg as ma on ma.UserId=ra.UserId inner join Tbl_Program as na on ra.PgmId=na.ProgramId and sa.MEventId='$MEID'";
$stmnt=sqlsrv_query($conn,$sql);
while($row = sqlsrv_fetch_array($stmnt,SQLSRV_FETCH_BOTH))
{
echo
'<tr align="center">
<td>'.$row["ProgramName"].'</td>
<td>'.$row["Name"].'</td>
<td>'.$row["Mob"].' </td>
<td>'.$row["Email"].'</td>
<td>'.$row["CName"].'</td>
<tr><td><br></td></tr>
</tr>';
}
?>
</table>
Both one are saved as .php
The data fetched from the DB (the select query) is working fine in the DB query.
Always the status is null.
I tried to see whether the status is fetching the data, whether it is mere the display part, which is the problem. But always the result to these are Null. I am a noob in these, so please throw me suggestions.
Thank You in advance.
Edit 1:
I tried to check whether this:
var MEventId=document.ParticularFest.EventId.value
is getting the MEventId, and yes it is. It is sending the MEventId too. The problem seems to be in the second php Page. I am not getting any return from that page. (I tried alert(status) in almost everywhere in the first php page, and it shows Null popup always :D )
Edit 2:
This is done in localhost. It is a college mini project
your alert is happening immediately, before the request finishes.
Try something like this.
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('test.html'); };
function makeRequest(url) {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
I have created 3 radio buttons:
Change Password - Change Name - Delete Account
When I select one of them it shows me a form that does something... but the problem is when I started to click submit button on the showing form it redirects me to another page, not the page I selected on action property in form
For example:
<form action = 'forget_pass.php' method = 'POST'>
when I click on submit button it should redirect me to page (forget_pass.php) but it redirects me to another page on my big project that I am working on currently.
My code that contains radio buttons:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("results").innerHTML = "";
return;
} else {
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("results").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_form.php?z="+str,true);
xmlhttp.send();
}
}
</script>
<form class = "form-horizontal">
<label><p style="color:red;">
<input type = "radio" name = "select" value = "pass" onChange="showUser(this.value)"> Change Password
<input type = "radio" name = "select" value = "name" onChange="showUser(this.value)"> Change Name
<input type = "radio" name = "select" value = "account" onChange="showUser(this.value)"> Delete Account
</p></label>
</form>
<div id = "results"> </div>
My code that showing the forms(get_form.php):
<?php
$z = $_GET['z'];
if($z == "pass")
{
// form
}
else if ($z == "account")
{
// form
}
else if($z == "name")
{
// form
}
?>
Hey, you programmers have been extremely helpful to me in the past, so I thought I'd ask my question here, again. It's probably a simple fix, but I'm new to JavaScript and Ajax.
What I have working is Ajax that writes to a a responseText stating, "LOCATION NOT FOUND" if it is not found when a text field loses focus. What I'd like to have done is to prevent the form from submitting if this responseText is present. I know how to prevent the form from submitting if a hidden field has the value LOCATION NOT FOUND, so I was thinking that having JavaScript populate the hidden field with the responseText might be the easiest solution? Not sure if that will work or how to go about doing it.
Here's my current JS:
<script type="text/javascript">
<!--
function newXMLHttpRequest()
{
var xmlreq = false;
if (window.XMLHttpRequest)
{
xmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
alert("Error: Unable to create an XMLHttpRequest.");
}
}
return xmlreq;
}
function getLocation(locationrouting)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + locationrouting, false);
getLocation.send(null); // getting location
var dv = document.getElementById("location_div");
if (getlocation.responseText === 'LOCATION NOT FOUND')
{
dv.style.color = "red";
}
else
{
dv.style.color = "black";
}
dv.innerHTML = getLocation.responseText;
}
//-->
</script>
Here is the applicable part of the form:
<form name="locationform" id="locationform" action="/PP?PAGE=POSTADDLOCATION" method="post">
<tr>
<td class="ajax_msg">
<div id="location_div">/div>
</td>
</tr>
<tr>
<td>
<div class="column1" id="locationrouting_div">
<p class="label_top">
*Routing Number</p>
<p class="field_top">
<input type="text" id="locationrouting" name="locationrouting" size="28" maxlength="9" onblur="getLocation(this.value);" /></p>
...
Thanks in advance!
As an option you can create javascript variable var isSubmitAllowed = true;, set this variable to false when location is not found and check this variable to prevent form submitting.
Something like:
<script type="text/javascript">
<!--
var isSubmitAllowed = true;
function newXMLHttpRequest()
{
var xmlreq = false;
if (window.XMLHttpRequest)
{
xmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
alert("Error: Unable to create an XMLHttpRequest.");
}
}
return xmlreq;
}
function getLocation(locationrouting)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + locationrouting, false);
getLocation.send(null); // getting location
var dv = document.getElementById("location_div");
if (getlocation.responseText === 'LOCATION NOT FOUND')
{
dv.style.color = "red";
isSubmitAllowed = false;
}
else
{
dv.style.color = "black";
isSubmitAllowed = true;
}
dv.innerHTML = getLocation.responseText;
}
//-->
</script>
Then in Form tag you can add onSubmit event handler that will return isSubmitAllowed value:
<form name="locationform" id="locationform" action="/PP?PAGE=POSTADDLOCATION" method="post" onSubmit="return isSubmitAllowed">
If you don't want the form to submit if the location isn't found, the easiest way would probably be just query the server before submitting. This be a lot easier to implement and to use than checking the status of a query that may or may not have happened previously via its side effects. :D