Sometimes the callback works, sometimes it dosen't... Suggestions

Hello my client side friends,
Server Side programmer looking for some help in the town of Javascript.

Building an admin section for a church’s event calendar (In Wordpress, Custom Plugin). The idea is for the to be able to setup different calendars, so they have to opportunity to show event’s for specific church groups, but also have the option of setting up a calendar for all events to show up. That parts all good.

What I’m running into trouble with is when they add a new calendar, I want the calendar to show up on the list of current calendars (which is right below the “Add Calendar” section) after they have set it up. And I’ve got it to work… sort of.

I’ve tried on Safari, FF, and Chrome. They’ve all 3 given me pretty much the same result, which is, sometimes the calendar will show up at the end of the table. Sometimes it won’t.

I have it setup so that when the user clicks the submit button, via ajax and xmlHttp, it runs a php script to validate the data, and then if the data’s valid put it into the database. After it’s sent to the db, I use the responseText function to “reload” the data in the given <div> tag. Right now it just chooses randomly if it want’s to refresh that data.

Any help would be deeply appreciated, and welcome.

Here’s the code I’m using:


//Add's the calendar... works fine.
function addCalendar() {
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	 {
		 alert ("Browser does not support HTTP Request");
		 return;
	 }
	var url="../wp-content/plugins/NewLife-EventCalendar/php/addCalendar.php";
	xmlHttp.onreadystatechange=displayAdd
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

//displays a list of the calendars in the <div> with the class "currCalendars" 
function displayCalendars() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	 {
		 document.getElementById("currCalendars").innerHTML=xmlHttp.responseText 
	 } 
}

//tells the xmlHttp object to run the php script and return the results....
function showCalendars() {
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	 {
		 alert ("Browser does not support HTTP Request");
		 return;
	 }
	var url="../wp-content/plugins/NewLife-EventCalendar/php/showCalendars.php";
	xmlHttp.onreadystatechange=displayCalendars
	xmlHttp.open("POST",url,true);
	xmlHttp.send(null);
}



Thanks!

Could you also post your displayAdd() function (used as callback in your addCalendar() function) ?

opps! Sorry bout that…


function displayAdd() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	 {
		 document.getElementById("calEditor").innerHTML=xmlHttp.responseText 
	 } 
}

Is xmlHttp defined in the global scope?
i.e., do you have “var xmlHttp;” in your script, outside of any functions?

Yes! First line of the file.


var xmlHttp;

Could it at all have todo with the data being refreshed BEFORE the actual data’s put into the db? Like it processes the displayCalendars() function before the data’s put into the database…

Since you’re checking for “if (xmlHttp.readyState==4 || xmlHttp.readyState==“complete”)” this is not likely…

Do the target divs (#currCalendars and #calEditor) always exist?

That’s what I was thinking, but just wanted to make sure.

The #currCalendars and #calEditor div’s are always existent yes.

Here are the PHP files id you wanna take a look:

addCalendar.php


<?php
	require_once('../../../../wp-load.php');
	global $wpdb;
?>
<h2>New Calendar</h2>
    <div id="calResults">
    <?php
        if(isset($_POST['addCal'])) {
			echo "<ul>";
            if(empty($_POST['calName'])) {
				echo "<li class=\\"fault\\">** Please fill in all required feilds **</li>";
            }
			elseif($_POST['calType'] == "grid" && empty($_POST['numEvents'])) {
				echo "<li class=\\"fault\\">** Please enter the number of events **</li>";
			}
			elseif($_POST['calType'] == "grid" && !is_numeric($_POST['numEvents'])) {
				echo "<li class=\\"fault\\">** Please enter a numeric number of events **</li>";				
			}
			else {
				$name = $_POST['calName'];
				$calType = $_POST['calType'];
				$sponsor = $_POST['sponsor'];
				$numEvents = NULL;
				if(is_numeric($_POST['numEvents'])) {
					$numEvents = $_POST['numEvents'];
			}
                
			$sql = "INSERT INTO ".$wpdb->prefix."event_calendars VALUES (NULL, '".$name."', '".$calType."', '".$sponsor."', '".$numEvents."', NOW())";
			if($result = $wpdb->query($sql)) {
				unset($_POST['calName']);
				unset($_POST['calType']);
				unset($_POST['sponsor']);
				unset($_POST['numEvents']);
			}
		}
			echo "</ul>";
	}
    ?>
    </div>
    <form onsubmit="return ajaxform(this);" method="post" id="addCalendar">
		<table>
        	<tr>
            	<td><label>Name: <em>(*Required)</em></label><input type="text" name="calName" value="<?php if(isset($_POST['calName'])){echo stripslashes($_POST['calName']);} ?>"/></td>
                <td><label>Sponser: </label>
                    <select name="sponsor">
                	<?php
			$sql = "SELECT sid, sponsorName FROM ".$wpdb->prefix."event_sponsors";
                        if($results = $wpdb->get_results($sql)) {
                            foreach($results as $result) {
                                echo "<option value='".$result->sid."'";

                                if($_POST['sponsor'] == $result->sid) {
					echo "selected=\\"selected\\"";
				}
				echo ">".$result->sponsorName."</option>\
";
                            }
			}
                        ?>
                	</select></td>
                <td><label>Calendar Type: </label>
                						<select name="calType">
                                            <option value="Full">Full Calendar</option>
                                            <option value="List" <?php if($_POST['calType'] == "grid"){echo "selected=\\"selected\\"";}?>>List</option>
                                        </select>
				</td>
                <td><label>Number of events: <em>("Grid" calendars)</em></label><input type="text" name="numEvents" value="<?php if(isset($_POST['numEvents'])){echo stripslashes($_POST['numEvents']);} ?>"/></td>
            </tr>
            <tr>
            	<td><input type="submit" name="addCal" value="Add Calendar" onclick="showCalendars()" /> <input type="reset" value="Clear Form"/></td>
            </tr>
        </table>
    </form>
    <div class="clear"></div>

and showCalendars.php


<?php
	require_once('../../../../wp-load.php');
	global $wpdb;
	$sql = "SELECT cid, name, type, sponsorName, eventCount, ".$wpdb->prefix."event_calendars.dateAdded FROM ".$wpdb->prefix."event_calendars, ".$wpdb->prefix."event_sponsors WHERE ".$wpdb->prefix."event_calendars.sponsor = ".$wpdb->prefix."event_sponsors.sid ORDER BY cid";
?>
<h2>Current Calendars</h2>
<?php

if($results = $wpdb->get_results($sql)) {

		$table = "<table class=\\"calendars\\">\
";
		$table .= "<thead>\\r\	";
			$table .= "<th class='eventID'>Id</th>\\r\	";
			$table .= "<th class='eventName'>Name</th>\\r\	";
			$table .= "<th class='type'>Type</th>\\r\	";
			$table .= "<th class='count'>Event Count</th>\\r\	";
			$table .= "<th class='sponsor'>Sponser</th>\\r\	";
		$table .= "</thead>\\r\\r";
		
		$offrow = 0;
		foreach($results as $result) {
			$table .= "<tr";
			if($offrow&#37;2 == 0) {
				$table .= " class='oddRow'";
			}
			$table .= ">\
\	";
				$table .= "<td class='eventID'>" . $result->cid. "</td>\\r\	";
				$table .= "<td class='eventName'>" . $result->name. "</td>\\r\	";
				$table .= "<td class='type'>". $result->type."</td>\\r\	";
				$table .= "<td class='count'>". $result->eventCount."</td>\\r\	";
				$table .= "<td class='sponsor'>" . $result->sponsorName. "</td>\\r\	";
				$table .= "<td class='edit'><a>Edit</a></td>\\r\	";
				$table .= "<td class='delete'><a>Delete</a></td>\\r";
			$table .= "</tr>\\r";
			$offrow++;
		}
		echo $table;
}
else {
	echo "<h3>***	You currently don't have any calendars	***</h3>";
}

?>
</table>



if(is_numeric($_POST['numEvents'])) {
                    $numEvents = $_POST['numEvents'];

is missing a closing brace (})

Your addCalendar() function most certainly doesn’t “add a calendar”. I doesn’t send any data? It simply sends a get request.

And, when you click the “Add calendar” submit button, you call the function showCalendars()? You also call ajaxForm(), which you haven’t posted.

These function names and the way they’re being used are confusing.

I can’t tell from the current info given, but my guess so far is that your issue is related to your use of a global variable. I think you’re probably sending off another ajax request before the first one finishes, clobbering the xmlhttp object in your global variable.

Okay… figured it out.

@crmalibu… I totally forgot that in my ajaxform() function it was already sending a request to the php script to add the script. So the add a calendar event was pretty much useless. Thanks for the “smack in the face”. Here’s the ajaxform function


function ajaxform(thisform)
{
    //General Purpose Ajax form submitter.
    //Written by Carl(bag) @ Thybag.co.uk

	//php page to process
	formhandler = '../wp-content/plugins/NewLife-EventCalendar/php/addCalendar.php';
	
    // Set up data variable
    var formdata = "";

    // Set up Ajax request variable
    try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");}  catch (e) { alert("Error: Could not load page.");}

    // Loop through form fields
    for (i=0; i < thisform.length; i++)
    {
         //Build Send String
         if(thisform.elements[i].type == "text") { //Handle Textbox's
                  formdata = formdata + thisform.elements[i].name + "=" + escape(thisform.elements[i].value) + "&";
         }
		 else if(thisform.elements[i].type == "textarea") { //Handle textareas
                  formdata = formdata + thisform.elements[i].name + "=" + escape(thisform.elements[i].value) + "&";
         }
		 else if(thisform.elements[i].type == "checkbox") { //Handle checkbox's
                 formdata = formdata + thisform.elements[i].name + "=" + thisform.elements[i].checked + "&";
         }
		 else if(thisform.elements[i].type == "radio") { //Handle Radio buttons
                  if(thisform.elements[i].checked==true){
                     formdata = formdata + thisform.elements[i].name + "=" + thisform.elements[i].value + "&";
                  }
         }
		 else {
                  //finally, this should theoretically this is a select box.
                  formdata = formdata + thisform.elements[i].name + "=" + escape(thisform.elements[i].value) + "&";
         }
    }

    //Send Ajax Request
    xmlhttp.onreadystatechange = function(){
               //Check page is completed and there were no problems.
               if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
                      //What to do once the form is submitted - to inform the user.
					 document.getElementById("calEditor").innerHTML=xmlhttp.responseText 
               		 updateCalendarList();
               }
    }
    //Make connection
    xmlhttp.open("POST", formhandler);
    //Set Headers
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //Send data
    xmlhttp.send(formdata);
    //stops form from submitting normally
    return false;
}


all I needed todo was add the updateCalendarList() function aka showCalendars() in the ajaxform function after it calls the responsetext, and it works perfectly now.

Thanks!

Thanks to you too ScallioXTX for helping too!