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

The most obvious thing is that your httprequests are synchronous.

Here, we learn that :

XMLHttpRequest supports both synchronous and asynchronous communications.
Note: You shouldn't use synchronous XMLHttpRequests because, due to the inherently asynchronous nature of networking, there are various ways memory and events can leak when using synchronous requests.
In versions of Firefox prior to Firefox 3, synchronous XMLHttpRequest requests blocked the user interface. In order to make it possible for the user to terminate frozen requests, Firefox 3 no longer does so.

I consider this explanation to be inadequate - no more than a smoke screen for a Firefox bug. There's no reason why any browser shouldn't support synchronous requests. After all, in every other respect Javascript is synchronous (and single threaded).

However, let's live with the reality. Avoid synchronous requests.

Change XMLHttpRequestObject.open("POST", formSource); , XMLHttpRequestObject.open("POST", formSource, false); , AJAX.open("POST", 'add2db.php', false); ,
to XMLHttpRequestObject.open("POST", ......., true); .

It may not cure the problem but needs fixing anyway.

Airshow

Ephemeral,

// If request is async (leaving off the false), server doesn't respond
// quick enough for proper functionality of error display

I'm afraid you need to find another workaround.

Oh yes, and change async: false , to async: true in the jQuery ajax.

Airshow

Well darn; I never even stopped to think about changing that to async and seeing if anything changed!

That took care of the first and more minor problem of having to click twice to view the initial error message. However, the second problem -- the page never updates with the correct *new* error message, despite a correct response from the server -- still exists.

Here is the new code:

// 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: true,
				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='http://www.mozilla.com/en-US/?from=sfx&amp;uid=289125&amp;t=456'><img src='http://sfx-images.mozilla.org/affiliates/Buttons/Firefox3.5/110x32_get.png' 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, true);
		// 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='http://www.mozilla.com/en-US/?from=sfx&amp;uid=289125&amp;t=456'><img src='http://sfx-images.mozilla.org/affiliates/Buttons/Firefox3.5/110x32_get.png' 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;
}

I'm still searching for a solution to this problem; would appreciate any new ideas or input.

However, the second problem -- the page never updates with the correct *new* error message, despite a correct response from the server -- still exists.

If I understand correctly, this is the handler that is supposed to respond to the error message returned from server-side :

success: function()
				{
					var chkStr = $('div#allErr').text();
					if ( chkStr.length != 0 )
					{
						$('div#allErr').removeClass('hidden');
					}
				}

If so, then it appears simply to unhide 'div#allErr' if it is not empty (thus showing the div's current contents), but doesn't update the contents.

Something like this would seem more appropriate :

success: function(message)
				{
					$('div#allErr').html(message);
					if ( message.length != 0 )
					{
						$('div#allErr').removeClass('hidden');
					}
					else
					{
						$('div#allErr').addClass('hidden');
					}
				}

Airshow

That certainly would be more logical if I were only passing back a message instead of new code for the form. The idea was that, even if someone has Javascript turned off, they could use the basic form without bells/whistles to be added later.

However, I am realizing that that goal would be quite impossible, since it requires AJAX/Javascript to load either the event form or the performance form.

That means that I need to do a bit of reworking with the code, then see if I still have this problem.

Maybe I have misunderstood. I thought a form was obtained by one AJAX call, then another AJAX call was used for server-side validation of user's data input.

It's not clear why a form and a status message would need to be passed back tp the page in the same AJAX response. However, it's not a problem if that's the case as techniques exist for responding with two or more data items exist (eg. JSON).

Airshow

No, you're correct, it's just that on the second AJAX call (to validate), the message is inside the HTML for the form; that way, I didn't have to do anything else in Javascript but "reveal" the error message if it was hidden.

No, you're correct, it's just that on the second AJAX call (to validate), the message is inside the HTML for the form; that way, I didn't have to do anything else in Javascript but "reveal" the error message if it was hidden.

So each form (whichever one is chosen then delivered by the server) is served up with a hidden error message already embedded? If so then your code should work.

The only thing I would say is that this is rather unconventional. You lose the opportunity to provide several types of error message (generated by the server-side validator) to give the user specific rather than general feedback.

Airshow

So each form (whichever one is chosen then delivered by the server) is served up with a hidden error message already embedded? If so then your code should work.

The only thing I would say is that this is rather unconventional. You lose the opportunity to provide several types of error message (generated by the server-side validator) to give the user specific rather than general feedback.

Airshow

The concept is right, except that
a) it doesn't work
and
b) it's not a general message. A different error message is embedded for each "kind" of error.


So, it should work like this: The user selects which form they need to complete. It is delivered to them with the div that the error message will be inside hidden. Whenever the user presses the submit button, then the entries are validated and the form is passed back again with an appropriate error message if there is an error, and then it is revealed. Eventually, the fields will be checked on each key press.

Ephemeral,

I'm away from home right now. I will read your posta gain when I get home tomorrow and see how your explanation changes my thinking.

Airshow

Ephemeral,

I really think you need to consider simplifying the design by reducing the reliance on AJAX in favour of some straightforward DHTML/DOM scripting. Keep as much as possible client-side.

You can do this as follows:

  1. Hard code both the forms on the page, each in a div with a unique id.
  2. In CSS, initially hide both forms ( display:none; )
  3. Hard code a "message" div on the page.
  4. Adjust $('input#button').live('click', function() {.....} to show/hide the forms (rather than fetch them from the server).
  5. Adjust the server-side code and SubmitEventForm's response handler to put success/error messages as appropriate into the hard coded "message" div, and to hide the current form as appropriate.

As far as I can see, there's no need ever to re-serve the forms, though you will probably need some way of clearing them of previous user entries when re-selected, which is pretty trivial.

After serving the page, the server only ever needs return messages.

You may also want to incorporate some sort of "UI locking" (eg. raise/lower some global javascript flag) to prevent more than one AJAX call being demanded before earlier call is complete. Remember there's no guarantee in which order the responses will arrive (due to asynchronicity).

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.