Page 1 of 2 12 LastLast
Results 1 to 10 of 15

Thread: Loading PHP page using AJAX

  1. #1
    Join Date
    Apr 2010
    Posts
    32
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Loading PHP page using AJAX

    Ok so I'm putting this under JavaScript as the problem is in the AJAX but it does contain PHP... So I'm trying to create a sign up form for a swim meet. The form has a drop down selector where you select the number of swimmers you want to sign up and then a javascript function loops over an AJAX request to add a PHP page which is the form inputs for each swimmer.

    So I have tested and when I have the AJAX function show an alert with the return from the AJAX and it returns the PHP page just fine... but when I try to have that function return the data to the original function that is looping over it the data comes back as undefined. I have included the pages below. You will see an events page as well.. this will be looped over in a similar way but have not coded that part yet as I need to first get this part working

    Thanks for any help... I would also gladly accept any suggestions for improvement as well

    signup_form.php
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title>Event Signup</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            <link href="signup.css" rel="stylesheet" type="text/css">
            <?php
    
    			if($_GET['swimmer_number'])
    			{
    				$swimmer_number = $_GET['swimmer_number'];
    			}
    			else
    			{
    				$swimmer_number = 1;	
    			}
    			if($_GET['event_number'])
    			{
    				$event_number = $_GET['event_number'];
    			}
    			else
    			{
    				$event_number = 1;	
    			}
    		?>
            <script type="text/javascript">
    		function changeSwimmerNumber(number_swimmers)
    		{
    			var swimmersHTML = "";
    			
    			for(i=1;i<=number_swimmers;i++)
    			{
    				swimmersHTML += getSwimmer(i);
    			}
    			
    			document.getElementById("swimmers_holder").innerHTML = swimmersHTML;
    		}
    		function getSwimmer(swimmer)
    		{
    			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)
    				{
    					var htmlReturn = xmlhttp.responseText;
    					return(htmlReturn);
    				}
    			}
    			xmlhttp.open("GET", "swimmer.php?swimmer="+swimmer, true);
    			xmlhttp.send();
    		}
    		</script>
        </head>
    	<body>
        	<form name="events" action="signup_result.php" method="get">
                <fieldset>
                	<legend>Event Signup</legend>
                	<p class="selecter_holder">
                        Number of Swimmers: 
                        <select id="swimmer_number" onChange="changeSwimmerNumber(this.value)">
                            <option value="1">1</option>
                            <option value="2" selected="selected">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                        </select>
                    </p>
                    <br />
                    <div id="swimmers_holder">
                	</div>
                </fieldset>
            </form>
        </body>
    </html>
    swimmer.php
    Code:
    <?php
    
    	if($_GET['swimmer'])
    	{
    		$swimmer = $_GET['swimmer'];	
    	}
    	else
    	{
    		echo("Foobar!");
    	}
    	
    ?>
    <fieldset id="swimmer_holder">
        <legend>Swimmer <?php echo($swimmer); ?></legend>
        <p class="inputs_holder">
            First name: <input type="text" name="firstName_<?php echo($swimmer); ?>" />
            <br />
            Last name: <input type="text" name="fastName_<?php echo($swimmer); ?>" />
        </p>
        <br />
        <p class="selecter_holder">
            Number of Events: 
            <select name="swimmer_number_<?php echo($swimmer); ?>">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4" selected="selected">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
                <option value="13">13</option>
                <option value="14">14</option>
                <option value="15">15</option>
            </select>
        </p>
        <br />
        <fieldset>
            <legend>Events</legend>
            <div id="events_holder_<?php echo($swimmer); ?>">
            	<p class="inputs_holder">
                    Event Number: <input type="text" name="eventNumber" />
                    <br />
                    Event Name: <input type="text" name="eventName" />
                </p>
            </div>
        </fieldset>
    </fieldset>
    <?php
    	$swimmer = '';
    ?>

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Two major problems. In no particular order, here:

    Code:
    		if (window.XMLHttpRequest)
    			{// code for IE7+, Firefox, Chrome, Opera, Safari
    				xmlhttp=new XMLHttpRequest();
    			}
    			else
    			{// code for IE6, IE5
    				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    			}
    Regardless of the method employed, xmlhttp is in the global scope. AJAX requests are not instantaneous. So before one is finished (if more than one swimmer), another overwrites it. But that doesn't even come into play until you realize that the return value of the onreadystatechange function is not the return value of the getSwimmer function.

    Once that's worked out, I found that the order in which the requests were completed wasn't necessarily the order in which they were made. So you could get swimmer 3 followed by 1, by 4, then 2, for example. All accounted for, but not in the order expected. So I worked out a way to store the return values in an array in the proper order until all were in, and then writing them to the output division:

    Code:
            <script type="text/javascript">
    		function changeSwimmerNumber(number_swimmers)
    		{
    			getSwimmer.ar = []; //create empty array to hold responses
    			getSwimmer.swimmers = 0; //create counter
    			
    			for(i=1;i<=number_swimmers;i++)
    			{
    				getSwimmer(i, number_swimmers); // pass the total number as the second parameter
    			}
    			
    		}
    		function getSwimmer(swimmer, number_swimmers)
    		{
    			var xmlhttp = {}; //create a local instance of xmlhttp that will not be overwritten by others (if any) in this run
    			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)
    				{
    					var htmlReturn = xmlhttp.responseText;
    					++getSwimmer.swimmers; //increment the counter
    					getSwimmer.ar[swimmer] = htmlReturn; //put this response in its proper order in the array
    					if(getSwimmer.swimmers == number_swimmers) //if the counter equals the total
    					document.getElementById("swimmers_holder").innerHTML = getSwimmer.ar.join('');
    				}
    			}
    			xmlhttp.open("GET", "swimmer.php?swimmer="+swimmer, true);
    			xmlhttp.send();
    		}
    		</script>
    Last edited by jscheuer1; 06-28-2010 at 07:52 PM. Reason: spelling
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jul 2008
    Posts
    128
    Thanks
    0
    Thanked 17 Times in 16 Posts

    Default

    Ok so I'm putting this under JavaScript as the problem is in the AJAX but it does contain PHP... So I'm trying to create a sign up form for a swim meet. The form has a drop down selector where you select the number of swimmers you want to sign up and then a javascript function loops over an AJAX request to add a PHP page which is the form inputs for each swimmer.
    You don't need AJAX to create a form. Just generate the elements using DOM methods. You can Google an explanation of doing it the proper way and the I.E. way.

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Here's a slightly more robust version:

    Code:
            <?php
    
    			if(isset($_GET['swimmer_number']))
    			{
    				$swimmer_number = $_GET['swimmer_number'];
    			}
    			else
    			{
    				$swimmer_number = 1;	
    			}
    			if(isset($_GET['event_number']))
    			{
    				$event_number = $_GET['event_number'];
    			}
    			else
    			{
    				$event_number = 1;	
    			}
    		?>
            <script type="text/javascript">
    		function changeSwimmerNumber(number_swimmers)
    		{
    			document.getElementById("swimmers_holder").innerHTML = "Loading . . ."; // display loading message while fetching contents
    			getSwimmer.ar = []; // create/reset empty array to hold responses
    			getSwimmer.swimmers = 0; // create/reset counter
    			
    			for(i = 1; i <= number_swimmers; ++i)
    			{
    				getSwimmer(i, number_swimmers); // pass the total number as the second parameter
    			}
    			
    		}
    		function getSwimmer(swimmer, number_swimmers)
    		{
    			var xmlhttp = {}; // create a local instance of xmlhttp that will not be overwritten by others (if any) in this run
    			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)
    				{
    					var htmlReturn = xmlhttp.responseText;
    					++getSwimmer.swimmers; // increment the counter
    					getSwimmer.ar[swimmer] = htmlReturn; // put this response in its proper order in the array
    					if(getSwimmer.swimmers == number_swimmers) // if the counter equals the total
    					{
    						document.getElementById("swimmers_holder").innerHTML = getSwimmer.ar.join('');
    					}
    				}
    			}
    			xmlhttp.open("GET", "swimmer.php?swimmer=" + swimmer, true);
    			xmlhttp.send();
    		}
    		changeSwimmerNumber.onload = function(){ // run onload to display some swimmer(s)
    			changeSwimmerNumber(document.getElementById('swimmer_number').value);
    		}
    		if (window.addEventListener){
    			window.addEventListener('load', changeSwimmerNumber.onload, false);
    		}
    		else if (window.attachEvent){
    			window.attachEvent('onload', changeSwimmerNumber.onload);
    		}
    		</script>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. The Following User Says Thank You to jscheuer1 For This Useful Post:

    corbo950 (06-28-2010)

  6. #5
    Join Date
    Apr 2010
    Posts
    32
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    Thank you so much it works great! I do have one question though.... in attempting to fix the problem I started rewriting the functions using jQuery.... just wondering if you think jQuery is a good thing to use.... again thanks

  7. #6
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I love jQuery. Just make sure you understand the parts of it you are using. It's not worth the effort or byte load though unless your site has other scripts that use it. In fact, the maximum benefit to jQuery is to use it for everything (all javascript on a site).
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  8. #7
    Join Date
    Apr 2010
    Posts
    32
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    Ok so i tired reading through your script and then applying it to the events part of the form as well and i got it to add them when selected but for some reason no matter what events number drop down I select it only effects the first swimmer ... what am i doing wrong? ... here is the code now:

    signup_form.php
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title>Event Signup</title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
            <link href="signup.css" rel="stylesheet" type="text/css">
            <script type="text/javascript" src="signup.js"></script>
        </head>
    	<body>
        	<form name="events" action="signup_result.php" method="get">
                <fieldset>
                	<legend>Event Signup</legend>
                	<p class="selecter_holder">
                        Number of Swimmers: 
                        <select id="swimmer_number" onChange="changeSwimmerNumber(this.value)">
                            <option value="1">1</option>
                            <option value="2" selected="selected">2</option>
                            <option value="3">3</option>
                            <option value="4">4</option>
                            <option value="5">5</option>
                        </select>
                    </p>
                    <br />
                    <div id="swimmers_holder">
                	</div>
                </fieldset>
            </form>
        </body>
    </html>
    swimmer.php
    Code:
    <?php
    	if(isset($_GET['swimmer']))
    	{
    		$swimmer_number = $_GET['swimmer'];
    	}
    	else
    	{
    		$swimmer_number = "Error could not load swimmer";	
    	}
    ?>
    <fieldset>
        <legend>Swimmer <?php echo($swimmer); ?></legend>
        <p class="inputs_holder">
            First name: <input type="text" name="firstName_<?php echo($swimmer); ?>" />
            <br />
            Last name: <input type="text" name="fastName_<?php echo($swimmer); ?>" />
        </p>
        <br />
        <p class="selecter_holder">
            Number of Events: 
            <select id="<?php echo($swimmer); ?>" name="event_number_<?php echo($swimmer); ?>" onChange="changeEventNumber(this.value, this.id)">
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4" selected="selected">4</option>
                <option value="5">5</option>
                <option value="6">6</option>
                <option value="7">7</option>
                <option value="8">8</option>
                <option value="9">9</option>
                <option value="10">10</option>
                <option value="11">11</option>
                <option value="12">12</option>
                <option value="13">13</option>
                <option value="14">14</option>
                <option value="15">15</option>
            </select>
        </p>
        <br />
        <fieldset>
            <legend>Events</legend>
            <div id="events_holder_<?php echo($swimmer); ?>">
            </div>
        </fieldset>
    </fieldset>
    <?php
    	$swimmer = '';
    ?>
    event.php
    Code:
    <?php
    
    	if(isset($_GET['event']))
    	{
    		$swimmer_number = $_GET['event'];
    	}
    	else
    	{
    		$swimmer_number = "Error could not load event";	
    	}
    	
    ?>
    <fieldset>
        <legend>Event <?php echo($event); ?></legend>
        <p class="inputs_holder">
            Event Number: <input type="text" name="eventNumber" />
            <br />
            Event Name: <input type="text" name="eventName" />
        </p>
    </fieldset>
    signup.js
    Code:
    // JavaScript Document
    function changeSwimmerNumber(number_swimmers)
    {
    	document.getElementById("swimmers_holder").innerHTML = "Loading . . ."; // display loading message while fetching contents
    	getSwimmer.ar = []; // create/reset empty array to hold responses
    	getSwimmer.swimmers = 0; // create/reset counter
    	
    	for(i = 1; i <= number_swimmers; ++i)
    	{
    		getSwimmer(i, number_swimmers); // pass the total number as the second parameter
    	}
    	
    }
    function getSwimmer(swimmer, number_swimmers)
    {
    	var xmlhttp = {}; // create a local instance of xmlhttp that will not be overwritten by others (if any) in this run
    	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)
    		{
    			var htmlReturn = xmlhttp.responseText;
    			++getSwimmer.swimmers; // increment the counter
    			getSwimmer.ar[swimmer] = htmlReturn; // put this response in its proper order in the array
    			if(getSwimmer.swimmers == number_swimmers) // if the counter equals the total
    			{
    				document.getElementById("swimmers_holder").innerHTML = getSwimmer.ar.join('');
    			}
    		}
    	}
    	xmlhttp.open("GET", "swimmer.php?swimmer=" + swimmer, true);
    	xmlhttp.send();
    }
    function changeEventNumber(number_events, swimmer_number)
    {
    	eventsHolder = "events_holder_" + swimmer_number; 
    	document.getElementById(eventsHolder).innerHTML = "Loading . . ."; // display loading message while fetching contents
    	getEvents.ar = []; // create/reset empty array to hold responses
    	getEvents.events = 0; // create/reset counter
    	
    	for(i = 1; i <= number_events; ++i)
    	{
    		getEvents(i, number_events, eventsHolder); // pass the total number as the second parameter
    	}
    	
    }
    function getEvents(swim_event, number_events, eventsHolder)
    {
    	var xmlhttp = {}; // create a local instance of xmlhttp that will not be overwritten by others (if any) in this run
    	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)
    		{
    			var htmlReturn = xmlhttp.responseText;
    			++getEvents.events; // increment the counter
    			getEvents.ar[swim_event] = htmlReturn; // put this response in its proper order in the array
    			if(getEvents.events == number_events) // if the counter equals the total
    			{
    				document.getElementById(eventsHolder).innerHTML = getEvents.ar.join('');
    			}
    		}
    	}
    	xmlhttp.open("GET", "forms/event.php?event="+ swim_event, true);
    	xmlhttp.send();
    }
    changeSwimmerNumber.onload = function()
    { // run onload to display some swimmer(s)
    	changeSwimmerNumber(document.getElementById('swimmer_number').value);
    }
    if (window.addEventListener)
    {
    	window.addEventListener('load', changeSwimmerNumber.onload, false);
    }
    else if (window.attachEvent)
    {
    	window.attachEvent('onload', changeSwimmerNumber.onload);
    }

  9. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    I see some logical inconsistencies in some of the code (not the signup.js).

    On swimmer.php you define $swimmer_number, but in the HTML portion of the page you reference $swimmer, which is undefined, though some PHP setups would understand it to mean the $_GET['swimmer'] value and it might work anyway. Mine is a little more strict, so I was getting an error. This (on swimmer.php):

    PHP Code:
    <?php
        
    if(isset($_GET['swimmer']))
        {
            
    $swimmer_number $_GET['swimmer'];
        }
        else
        {
            
    $swimmer_number "Error could not load swimmer";    
        }
    ?>
    should be:

    PHP Code:
    <?php
        
    if(isset($_GET['swimmer']))
        {
            
    $swimmer $_GET['swimmer'];
        }
        else
        {
            
    $swimmer "Error could not load swimmer";    
        }
    ?>
    Pretty much the same deal on event.php, where:

    PHP Code:
    <?php

        
    if(isset($_GET['event']))
        {
            
    $swimmer_number $_GET['event'];
        }
        else
        {
            
    $swimmer_number "Error could not load event";    
        }
        
    ?>
    should be:

    PHP Code:
    <?php

        
    if(isset($_GET['event']))
        {
            
    $event $_GET['event'];
        }
        else
        {
            
    $event "Error could not load event";    
        }
        
    ?>
    Once I fixed up that stuff, it worked fine. There would probably be some problems when the form is submitted. All resulting:

    HTML Code:
        <p class="inputs_holder">
            Event Number: <input name="eventNumber" type="text">
            <br>
            Event Name: <input name="eventName" type="text">
        </p>
    are the same. But other than that, it was fine. One potential problem could be the fact that you list the location of event.php (in signup.js) as:

    Code:
    xmlhttp.open("GET", "forms/event.php?event="+ swim_event, true);
    That makes the script look for it in the forms folder. Your other forms (signup_form.php and swimmer.php) are in the current folder.

    If the script can't find the event.php page it will get stuck on:

    Loading . . .
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #9
    Join Date
    Apr 2010
    Posts
    32
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    Thanks I'm so new to JS that i kept assuming the problem was there... should have just checked my PHP lol

  11. #10
    Join Date
    Apr 2010
    Posts
    32
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    So now I added a for loop to the getSwimmer function to add the events when each swimmer loads but i can only get one swimmer to load the events... like if i set it to load into number 2 then number 2 loads... and if I replace the changeEventNumber function with an alert it pops up 1 & 2 like it should for i but if I add an alert infront of the changeEventNumber function it will only show 1 ... why is this?

    Code:
    function getSwimmer(swimmer, number_swimmers)
    {
    	var xmlhttp = {}; // create a local instance of xmlhttp that will not be overwritten by others (if any) in this run
    	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)
    		{
    			var htmlReturn = xmlhttp.responseText;
    			++getSwimmer.swimmers; // increment the counter
    			getSwimmer.ar[swimmer] = htmlReturn; // put this response in its proper order in the array
    			if(getSwimmer.swimmers == number_swimmers) // if the counter equals the total
    			{
    				document.getElementById("swimmers_holder").innerHTML = getSwimmer.ar.join('');
    				for(i = 1; i <= number_swimmers; ++i)
    				{
    					changeEventNumber(4, i);
    				}
    			}
    		}
    	}
    	xmlhttp.open("GET", "swimmer.php?swimmer=" + swimmer, true);
    	xmlhttp.send();
    }

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •