I'm having two Ajax-related problems on a page I am working on at the moment. http://www.utm.edu/departments/acadpro/library/openmic/add2db.php
On this page, I have two buttons that use Ajax to fetch two separate forms and put them into a chosen div; that part works like a charm.
On said forms, there is a div that is meant to display any necessary error messages when the submit button is clicked. However, on the first time the page is visited and the form is chosen, the div won't display the error message. Only after refreshing the page/choosing the form a second time will the message show. I've been checking the response from the server via Firebug and the response is correct, it just seems like the page isn't updating correctly.
Secondly, once I refresh or choose the form again and the error message begins to show, if I enter values into the form fields and should be getting a different error message, it never updates. Once again, the server response is correct, but for some reason the page just isn't updating to reflect the new message.
I have been using the date field on the New Event form for testing; if you have Firebug, you should be able to see that I am getting the desired response from the server (look in the allErr div), but the HTML isn't changing with it. I have tried both using my own Ajax functions and using jQuery's Ajax implementation, but both give me the same problems. What am I doing wrong?
// JavaScript Document
// Megan Tucker
// 11/18/2009
// JS for add2db.php page
var unloadFlag = true;
window.onbeforeunload = PromptControl;
$(document).ready(function(){
$('input#button')
.live('click', function()
{
if ( $(this).attr("name") == "event" ) // can't use any other selectors for these if statements
{
getForm('add2db.php?a=' + new Date().getTime(), 'targetForm', 'event');
unloadFlag = false;
}
else if ( $(this).attr("name") == "performance" )
{
getForm('add2db.php?a=' + new Date().getTime(), 'targetForm', 'performance');
unloadFlag = false;
}
});
$('input#createEvent')
.live('click', function()
{
unloadFlag = false;
var date = $('#popUpDate:input').val();
var sTime = $('#startTime:input').val();
var eTime = $('#endTime:input').val();
//SubmitEventForm('add2db.php?a=' + new Date().getTime(), 'targetForm', 'event', date, sTime, eTime);
$.ajax
({
url: 'add2db.php?a=' + new Date().getTime(),
async: false,
type: "POST",
data: "&display=none&formChoice=event&date=" + date + "&sTime=" + sTime + "&eTime=" + eTime,
success: function()
{
var chkStr = $('div#allErr').text();
if ( chkStr.length != 0 )
{
$('div#allErr').removeClass('hidden');
}
}
});
}
);
}); // end "main"
function getForm(formSource, divId, formChoice)
{
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (XMLHttpRequestObject)
{
var obj = document.getElementById(divId);
XMLHttpRequestObject.open("POST", formSource);
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("display=none&formChoice=" + formChoice);
}
else
{
var obj = document.getElementById(divId);
obj.innerHTML = "Sorry, your browser is not Ajax-enabled. <a href='(URL address blocked: See forum rules)=sfx&uid=289125&t=456'><img src='(URL address blocked: See forum rules) alt='Spread Firefox Affiliate Button' border='0' /></a>";
} // end if
} // end function
function SubmitEventForm(formSource, divId, formChoice, date, sTime, eTime)
{
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest)
{
XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
if (XMLHttpRequestObject)
{
var obj = document.getElementById(divId);
XMLHttpRequestObject.open("POST", formSource, false);
// If request is async (leaving off the false), server doesn't respond
//quick enough for proper functionality of error display
XMLHttpRequestObject.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
{
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send("display=none&formChoice=" + formChoice + "&date=" + date + "&sTime=" + sTime + "&eTime=" + eTime);
}
else
{
var obj = document.getElementById(divId);
obj.innerHTML = "Sorry, your browser is not Ajax-enabled. <a href='(URL address blocked: See forum rules)=sfx&uid=289125&t=456'><img src='(URL address blocked: See forum rules) alt='Spread Firefox Affiliate Button' border='0' /></a>";
} // end if
return;
}
function PromptControl()
{
if (unloadFlag)
{
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX)
{
AJAX.open("POST", 'add2db.php', false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("action=unset");
}
}
else if (!unloadFlag)
{
unloadFlag = true;
}
return;
}
<?php
session_start();
//////////////////////////////////////////////////////
PrintMain();
//////////////////////////////////////////////////////
// there is a javascript function that, on window out, unsets the variable keeping the header from displaying
if (@$_REQUEST['action'] == 'unset')
{
unset($_SESSION['display']);
}
//////////////////////////////////////////////////////
// tells which form to post
if ($_POST["formChoice"] == "event")
{
PrintEventForm();
}
else if ($_POST["formChoice"] == "performance")
{
PrintPerformanceForm();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS BELOW //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*************************
* Function PrintMain
* Arguments: none
* Uses: session variables
* Prints out the body of the page when it is needed, and
* keeps it from displaying when a form is chosen.
*************************/
function PrintMain()
{
/* SESSION VARIABLES -- control whether or not to display header and form selection buttons. */
$status = $_POST["display"];
if (!isset($_SESSION['eform']))
$_SESSION['eform'] = false; // implements functionality form validation
if (!isset($_SESSION['pform']))
$_SESSION['pform'] = false;
if ($status == "none")
{
$_SESSION['display'] = false; // session variables control what part of the page to display at what time
}
else
{
$_SESSION['display'] = true;
}
/* END SESSION VARIABLE STUFF */
if ($_SESSION['display'] == true) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "(URL address blocked: See forum rules)">
<html xmlns="(URL address blocked: See forum rules)">
<head>
<title>Open Mic Night at the Paul Meek Library - Add New Event</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- my page stuff -->
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script type="text/javascript" src="(URL address blocked: See forum rules)"></script>
<script type="text/javascript" src="(URL address blocked: See forum rules)"></script>
<!-- datepick stuff -->
<link rel="stylesheet" type="text/css" href="(URL address blocked: See forum rules)" />
<script type="text/javascript" src="(URL address blocked: See forum rules)"></script>
<!-- timepickr stuff -->
<style>
@import "(URL address blocked: See forum rules)";
@import "(URL address blocked: See forum rules)";
@import "(URL address blocked: See forum rules)";
</style>
<script type="text/javascript" src="(URL address blocked: See forum rules)"></script>
</head>
<body>
<div id="formcontent">
<h1>
Add a New Event Date -- Add a New Performance Time
</h1>
<p>
Choose one of the buttons below to either add a new event date or add a new performance time. Your selection will then load below, where the text "Correct form will appear here" is located.
</p>
<form>
<input type="button" name="event" id="button" value="Add a New Event Date" />
<input type="button" name="performance" id="button" value="Add a New Performance Time" />
</form>
<div id="targetForm">
Correct form will appear here
</div>
<?php include("formfooter-nocount.php");
}
return;
}
// END PrintMain
function PrintEventForm()
{
if ($_SESSION['eform'] == true)
{
$_SESSION['eform'] = false;
$date = $_POST['date'];
$startTime = $_POST['sTime'];
$endTime = $_POST['eTime'];
$message1 = array();
$message2 = array();
CheckMyDate($date, $message1);
if (!$message1['ok'])
{
$_SESSION['eform'] = true;
$message = "There was a problem with your request: <br />";
$message .= $message1['msg'];
}
}
else
{
$_SESSION['eform'] = true;
}
if ($_SESSION['eform'] == true)
{
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="POST" id="eventform">
<div id="allErr" class="hidden">
<?php
if ($message)
echo $message;
?>
</div>
<div class="tablecontainer">
<div class="cap">
<h2>Add a New Event</h2>
</div>
<div id="dateRow" class="tr">
<div id="dateLabel" class="td">Date: </div>
<div id="dateInput" class="td"><input id="popUpDate" name="popUpDate" class="popUpDate" autocomplete="off" size="30" value="<?php echo $date; ?>" /></div>
<div id="dateError" class="td"></div>
</div>
<div id="startTimeRow" class="tr">
<div id="startTimeLabel" class="td">Start Time: </div>
<div id="startTimeInput" class="td"><input id="startTime" name="startTime" class="pickTime" autocomplete="off" size="30" value="<?php echo $startTime; ?>" /></div>
<div id="startTimeError" class="td hidden"></div>
</div>
<div id="endTimeRow" class="tr">
<div id="endTimeLabel" class="td">End Time: </div>
<div id="endTimeInput" class="td"><input id="endTime" name="endTime" class="pickTime" autocomplete="off" size="30" value="<?php echo $endTime; ?>" /></div>
<div id="endTimeError" class="td hidden"></div>
</div>
</div>
<input type="button" id="createEvent" value="Add Event" name="createEvent" />
</form>
<?php
}
return;
} // END PrintEventForm
function PrintPerformanceForm()
{
?>
<form action="<?php echo $_SERVER['SCRIPT_NAME']; ?>" method="POST">
<div class="tablecontainer">
<div class="cap">
<h2>Add a New Performance to an Existing Event</h2>
</div>
<div class="tr">
<div class="td">Date: </div>
<div class="td">
<select size="1" name="date" id="date">
<option value="" selected="selected" />
</select>
</div>
</div>
<div class="tr">
<div class="td">Time: </div>
<div class="td">
<select size="1" name="time" id="time">
<option value="" selected="seleted" />
</select>
</div>
</div>
<div class="tr">
<div class="td">Name of Performer: </div>
<div class="td">
<input type="text" id="name" name="name" size="30" />
</div>
</div>
</div>
<input type="submit" value="Add Performance" name="add" />
</form>
<?php
return;
} // END PrintPerformanceForm
function CheckMyDate($myDate, &$resp)
{
$events = GetEvents();
if (!$myDate)
{
$resp['ok'] = false;
$resp['msg'] = "You must enter a date.";
}
else if (!preg_match("%^((?:19|20)\d\d)/(0[1-9]|1[012])/(0[1-9]|[12][0-9]|3[01])$%", $myDate))
{
$resp['ok'] = false;
$resp['msg'] = "Date must be in format YYYY/MM/DD";
}
else
{
// check if date is already taken
$arraySize = count($events);
$testVal = true;
for ($myRow = 0; $myRow < $arraySize; $myRow++)
{
$arb = $events[$myRow]['Date'];
if (levenshtein($arb, $myDate) == 0)
{
$resp['ok'] = false;
$resp['msg'] = "There is already an event on this date";
$testVal = false;
break;
}
} // end for
//print $testVal;
// check if date is actually valid
$groups = array();
preg_match('%^((?:19|20)\d\d)/(0[1-9]|1[012])/(0[1-9]|[12][0-9]|3[01])$%', $myDate, $groups);
if ($groups[3] == 31 && ($groups[2] == 4 || $groups[2] == 6 || $groups[2] == 9 || $groups[2] == 11))
{
$resp = array('ok' => false, 'msg' => "Date is 31 in a month with only 30 days");
}
else if ($groups[2] == 2 and $groups[3] >= 30)
{
$resp = array('ok' => false, 'msg' => "Date is 30 or 31 in February");
}
else if ($groups[2] == 2 and $groups[3] == 29 and !($groups[1] % 4 == 0 and ($groups[1] % 100 != 0 or $groups[1] % 400 == 0)))
{
$resp = array('ok' => false, 'msg' => "Date is 29 in February and it is not a leap year");
}
if ($testVal == true)
{
$resp = array('ok' => true, 'msg' => "This date is available");
} // end if
} // end else
return;
}
function CheckMyTimes($sTime, $eTime)
{
if (!$sTime && !$eTime)
{
$resp = array('ok' => false, 'msg' => "You must enter a start and end time");
}
else if (!$sTime && $eTime)
{
$resp = array('ok' => false, 'msg' => "You must enter a start time");
}
else if ($sTime && !$eTime)
{
$resp = array('ok' => false, 'msg' => "You must enter an end time");
}
else if (!preg_match('%^(0[1-9]|1[012]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]) (am|pm)$%', $sTime, $groups))
{
$resp = array('ok' => false, 'msg' => "Start time must be in the format HH:MM am/pm");
}
else if (!preg_match('%^(0[1-9]|1[012]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]) (am|pm)$%', $eTime, $groups))
{
$resp = array('ok' => false, 'msg' => "End time must be in the format HH:MM am/pm");
}
else
{
$resp = array('ok' => true, 'msg' =>"Start and end times good");
}
return $resp;
}
function GetEvents()
{
//Database connection details
$host = "mysql.utm.edu";
$mysql_user = "library";
$mysql_password = "pmlib";
$mysql_db = "library";
//make connection with mysql and select the database
$mysql_connect = mysql_connect($host, $mysql_user, $mysql_password);
$db_select = mysql_select_db($mysql_db);
//getting some times for later use (in query and performance)
$nowTime = time();
$today = date("Y/n/j", time());
$results = mysql_query("SELECT DATE_FORMAT(eventTime, '%Y/%m/%d') as eDate,DATE_FORMAT(eventTime, '%H:%i') as eTime,name FROM eventcal_test WHERE eventTime >= '$today' ORDER BY eDate ASC") or die(mysql_error());
while($row = mysql_fetch_assoc($results))
{
$events[] = array('Date' => $row['eDate'], 'Time' => $row['eTime'], 'Performer' => $row['name']);
}
//print_r($events);
return $events;
}
?>