Ajax Talk - Asynchronous javascript and xml discussion board
 FAQ   Search    Usergroups      Register   Profile   Check your messages   Log in 
Signup now to enjoy a range of free membership advantages !!
Ajax Talk - Moderators Wanted
Ajax code only running on first select

 
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help
View previous topic :: View next topic  
Author Message
mikecollins
New one
New one


Joined: 23 Oct 2007
Posts: 4

PostPosted: Tue Oct 23, 2007 2:13 am    Post subject: Ajax code only running on first select Reply with quote

Hi,

I believe this is an Ajax topic, and need some help. snippett below, webpage at: http://lamp.cse.fau.edu/~scolli26/mp3/enterjob.php. There is a dropdown that is supposed to show up for the option picked, which it does, but it does not change for other options picked. Options 1-3 are supposed to show the same options.

I have the following html:
Code:
<select id="selectJobtype" name="selectJobtype" onchange="GetOptions(this, this.value)">


This fires an Ajax event:


Code:
/* The following function creates an XMLHttpRequest object
   based on the browser being used. */
function CreateRequestObject()
{
   var request_o;
   var browser = navigator.appName;
   
   if(browser == "Microsoft Internet Explorer")
      request_o = new ActiveXObject("Microsoft.XMLHTTP");
   else
      request_o = new XMLHttpRequest();

   return request_o;
}

/* The variable http will hold the XMLHttpRequest object. */
var http = CreateRequestObject();

function GetOptions(control, value)
{
   /* Function to call once a response has been received */
   http.onreadystatechange = CheckState;
   
   /* Create the request */
   http.open('get', '/~scolli26/mp3/enterjob_2.php?action=getOptions&jobtype=' + value, true);         
   /* Send the data */
   http.send(null);
}

/* Function called to handle the list that was returned from the php file.. */
function CheckState()
{
   /* Make sure that the transaction has finished
      0: Uninitialized
      1: Loading
      2: Loaded
      3: Interactive
      4: Finished
   */

   /* Check the response of the XMLHttpRequest */
    if(http.readyState == 4)
   {

   }
}


I've noticed that everything works fine the first time through, but the second and other times through, the Ajax event does not seem to fire.

Can someone tell me why it is only firing only once?
Back to top
View user's profile Send private message Visit poster's website
Jesdisciple
Frequent Poster
Frequent Poster


Joined: 20 Oct 2007
Posts: 36
Location: Tejas

PostPosted: Tue Oct 23, 2007 8:20 pm    Post subject: Reply with quote

Mike, in my saved copy of your application as interpreted by Internet Explorer, the first click does nothing and the second click generates an error about "Unknown name" for line 31 (just below your call to http.open()), character 2, in tools.js. (It says the error is from enterjob.php, but I know it's from the JavaScript because changing the number of lines in the JS changed the line number in the error, whereas doing the same in the page did not.) I'm on a public computer right now, but should be able to test it better at home, where I have Firefox and Opera.

If you could figure out what causes this and give me a fix for it, that would help. The problem might be caused by my lack of your PHP code, though I don't see how it would be; if you don't mind posting (or privately messaging) that, it might help us toward a working version of the application for me to test.
_________________
In ALL things, strive for ><>,
Chris
Back to top
View user's profile Send private message Visit poster's website AIM Address MSN Messenger
mikecollins
New one
New one


Joined: 23 Oct 2007
Posts: 4

PostPosted: Tue Oct 23, 2007 11:33 pm    Post subject: Reply with quote

Thanks for looking at this...It has me stumped.

Here is the full code (two different php pages and one js page)

enterjob.php
Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>C&amp;Js Home Services</title>
    <link href="main.css" rel="stylesheet" type="text/css" />
    <script src="scripts/tools.js" type="text/javascript"></script>
</head>
<body>
    <div id="wrapper">
        <div id="branding">
            <img src="images/branding2.gif" alt="C&amp;Js Home Services" />
        </div>
        <div id="navigation">
            <ul>
                <li class="first"><a href="index.php">Home</a></li>
                <li><a href="enterjob.php">Enter Job</a></li>
                <li><a href="services.php">Services</a></li>
                <li><a href="contactus.php">Contact Us</a></li>
            </ul>
        </div>
        <div id="body">
            <form id="enterJob">
                <div id="informationArea">
                    <br />
                    <label class="bold">Job Type:</label>
                    <select id="selectJobtype" name="selectJobtype" onchange="GetOptions(this, this.value)">
                      <option value="0">--Select Service--</option>
                      <option value="1">Mow Lawn</option>
                      <option value="1">Edge Lawn</option>
                      <option value="1">Fertilize Lawn</option>
                      <option value="2">Trim Bushes/Trees</option>
                      <option value="3">Power Wash</option>
                      <option value="4">Clean Windows</option>
                    </select>
                    <label id="lblSelectArea" class="bold" style="display: none;">Area:</label>
                    <select id="selectArea" name="selectArea" style="display: none;" onchange="GetYardSize(this, this.value)">
                       
                    </select>                   

                    <label id="lblYardSize" class="bold" style="display: none;">Yard Size:</label>
                    <select id="yardSize" name="yardSize" style="display: none;">
                       
                    </select>                   
                   
                    <br />
                    <br />
                    <label class="bold">Description/Special Instructions:</label>
                    <br />
                    <textarea id="jobdescription" name="jobdescription" cols="50" rows="10"></textarea>
                    <br />
                    <br />
                    <input id="btnSubmit" type="submit" value="Submit" /></div>
            </form>
        </div>
        <div id="footer">C&amp;Js Home Services &copy; 2007
        </div>
    </div>
</body>
</html>


enterjob_2.php
Code:

<?php
$host="localhost"; // Host name
$username="myusername"; // Mysql username
$password="myuserpassword"; // Mysql password
$db_name="testdatabase"; // Database name

if($_GET['action'] == 'getOptions'){
   // Connect to server and select databse.
   mysql_connect("$host", "$username", "$password")or die("cannot connect");
   mysql_select_db("$db_name")or die("cannot select DB");

    switch($_GET['jobtype']){
        case 0:

            break;
           
        case 1: //Mow, trim, or edge
         $sql="Select id, yardtype From YardTypes";
         $result = mysql_query($sql);
         
         if (empty($result))
            echo $sql, '<br /><br />', mysql_error();
         
         $temp='';
         
         while ($row = mysql_fetch_array($result) )
         {
            $temp = $temp.$row['id'].":".$row['yardtype'].";";
         }
            
         echo ($temp);
            break;
           
        case 2: //Internet
         $sql="Select id, yardtype From YardTypes";
         $result = mysql_query($sql);
         
         if (empty($result))
            echo $sql, '<br /><br />', mysql_error();
         
         $temp='';
         
         while ($row = mysql_fetch_array($result) )
         {
            $temp = $temp.$row['id'].":".$row['yardtype'].";";
         }
            
         echo ($temp);
            break;
       
        case 3:   //PowerWash
         $sql="Select id, options From powerwashoptions";
         $result = mysql_query($sql);
         
         if (empty($result))
            echo $sql, '<br /><br />', mysql_error();
         
         $temp='';
         
         while ($row = mysql_fetch_array($result) )
         {
            $temp = $temp.$row['id'].":".$row['options'].";";
         }
            
         echo ($temp);
            break;

      case 4:
         $sql="Select id, yardtype From YardTypes";
         $result = mysql_query($sql);
         
         if (empty($result))
            echo $sql, '<br /><br />', mysql_error();
         
         $temp='';
         
         while ($row = mysql_fetch_array($result) )
         {
            $temp = $temp.$row['id'].":".$row['yardtype'].";";
         }
            
         echo ($temp);
            break;
           
        default:   //User has selected all required information...save job
         $jobtype=$_POST['jobtype'];
         $jobdescription=$_POST['jobdescription'];

         $sql="INSERT INTO $tbl_name (userid, jobtype, jobdescription) VALUES('$userid', '$jobtype', '$jobdescription')";

         if (mysql_query($sql))
            header("location:thankyou.php");
         else
            echo "The server is temporarily unavailable. We apologize for the inconvenience.";
           
            break;     
    }   
}
?>


tools.js
Code:

/* The following function creates an XMLHttpRequest object
   based on the browser being used. */
function CreateRequestObject()
{
   var request_o;
   var browser = navigator.appName;
   
   if(browser == "Microsoft Internet Explorer")
      request_o = new ActiveXObject("Microsoft.XMLHTTP");
   else
      request_o = new XMLHttpRequest();

   return request_o;
}

/* The variable http will hold the XMLHttpRequest object. */
var http = CreateRequestObject();
var selectedValue = 0;

function GetOptions(control, value)
{
    //This is the value that the user selected. It will be used to determine
    //what some of the labels say.
    selectedValue = value;
   
   /* Function to call once a response has been received */
   http.onreadystatechange = CheckState;
   
   /* Create the request */
   http.open('get', '/~scolli26/mp3/enterjob_2.php?action=getOptions&jobtype=' + value, true);
         
   /* Send the data */
   http.send(null);
}

/* Function called to handle the list that was returned from the php file.. */
function CheckState()
{
   /* Make sure that the transaction has finished
      0: Uninitialized
      1: Loading
      2: Loaded
      3: Interactive
      4: Finished
   */

   /* Check the response of the XMLHttpRequest */
    if(http.readyState == 4)
   {
      var response = http.responseText;
      var control = document.getElementById('selectArea');

      //Change appropriate labels and add correct option value.
      switch (selectedValue)
      {
          case "1":
              AddOption(control, "--Select Yard Size--", "0");
              break;
             
          case "2":
              AddOption(control, "--Select Number of Trees/Bushes--", "0");
              break;
             
          case "3":
              AddOption(control, "--Select Area--", "0");
              break;
             
          default:
              AddOption(control, "--Select # of Windows--", "0");
              break;
      }

      /* Update the required element */
      if (selectedValue == 1 || selectedValue == 3)
      {
          var array1 = new Array();
          var array2 = new Array();
          array1 = response.split(";");
          
          for (var x = 0; x < array1.length - 1; x++)
          {
              var option = array1[x];
              array2 = option.split(":");
              AddOption(control, array2[1], array2[0])
          }
      }
      else
      {
          for (var i = 1; i < 51; i++)
          {
              AddOption(control, i, i);
          }
      }
   }
}

function AddOption(selectbox, text, value )
{
    var label = document.getElementById('lblSelectArea');
   
    label.style["display"] = "inline";
    selectbox.style["display"] = "inline";
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
   
   
}
Back to top
View user's profile Send private message Visit poster's website
Jesdisciple
Frequent Poster
Frequent Poster


Joined: 20 Oct 2007
Posts: 36
Location: Tejas

PostPosted: Wed Oct 24, 2007 2:55 am    Post subject: Reply with quote

There's some difference between the code you use and the code you posted. The code you use gives no errors in IE, FF, or OP; the code you posted gives:

Internet Explorer wrote:
Line: 26
Char: 1
Code:0
URL: enterjob.php


Firefox wrote:
Error: GetOptions is not defined
Source File: enterjob.php
Line: 1


Opera wrote:
JavaScript - http://localhost/help/enterjob/enterjob.php
Event thread: change
Error:
name: ReferenceError
message: Statement on line 1: Reference to undefined variable: getOptions
Backtrace:
Line 1 of script
getOptions(this, this.value);
At unknown location
[statement source code not available]


As a side note, JSLint (documentation) is an effective syntax validator (and convention enforcer). It has annoyingly high standards (and this is why I have syntactically modified my version of your code), but has helped me several times before. It didn't produce any helpful errors this time, but you might want to use it the next time.

Try this:
1) Copy and paste your posted code into new files in a new folder on your server.
2) Load the new enterjobs.php and tell me what it does.
3) If it gives the errors shown above, try to figure out how to get the real code to me; if not, we'll have to figure that out ad-hoc.

As this forum seems to have been abandoned by its regulars well before I found it three days ago, you should also try posting your question somewhere else, i.e. http://w3schools.invisionzone.com/index.php?showforum=26. I'm trying to contact "deejay", who seems to have been in charge, to find out what happened and if it can be reversed.
_________________
In ALL things, strive for ><>,
Chris
Back to top
View user's profile Send private message Visit poster's website AIM Address MSN Messenger
mikecollins
New one
New one


Joined: 23 Oct 2007
Posts: 4

PostPosted: Wed Oct 24, 2007 3:05 am    Post subject: Reply with quote

Thanks for trying...

I don't know if you have been to the website, but I am actively working in it now (changing stuff) and am getting some stuff figured out. I have tried it in Firefox and the http request fires everytime.

If you mean by the "code I posted", as in the code I gave in the initial post, that is a very stripped down version. What I sent after your first reply should have worked, but maybe I goofed something up copying it.

Like I said...I am making some headway and actively changing stuff now. I'll post back on Thursday if I have not gotten it all figured out.

Thanks a lot for your help.
Back to top
View user's profile Send private message Visit poster's website
mikecollins
New one
New one


Joined: 23 Oct 2007
Posts: 4

PostPosted: Sat Oct 27, 2007 8:02 pm    Post subject: Found out why Ajax code was only running once Reply with quote

In case anyone reads this, I found out why my ajax code wa only running once. This only occurred with IE. With Firefox, it ran everytime anyway.

Since it was my first time with Ajax, I copied some code from an internet posting. In its ajax request, it had the following variable declared globally:

var http = CreateRequestObject();

Since this variable was declared outside a function, IE only called it once. This made me think that the code was only running once. In fact, the code was running everytime, but after the first run, the request object always in a readystate of 4, which kept it from running again.

This only happened in IE. When I ran it in Firefox, it always ran. Course, now that I know what the problem was, I now have the variable delcaration declared globally, with it being instantiatd inside the function I am calling to check it.

Hope this helps any other newbie to ajax...
Back to top
View user's profile Send private message Visit poster's website
Display posts from previous:   
Post new topic   Reply to topic    Ajaxtalk.com Forum Index -> AJAX Help All times are GMT
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
 Advertisements
 XML & Copyright Notice 
    


Powered by phpBB © 2001, 2005 phpBB Group

What is according to Wikipedia: Ajax Web2.0 XML E4X


Link to our site:

  


del.icio.us digg spurl wists simpy newsvine blinklist furl blogmarks yahoo! myweb smarking ma.gnolia segnalo reddit fark technorati cosmos


Normal Bookmark


Partner Button Links:
Codecrunch.com: Webmaster Tutorials    One Ajax


Partner Text Links:
quomon | web20log | ajaxmatters | tableless | 456bereastreet | music charts | gift ideas | competitions | free xbox 360 | link trade ?


Credits:
it consultancy & project management lead generation zoekmachine optimalisatie steal these buttons seo expert