SitePoint Sponsor

User Tag List

Results 1 to 10 of 10

Hybrid View

  1. #1
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Hiding from the world
    Posts
    357
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    ajax onsubmit form not working

    Hi,
    having a bit of trouble with a simple ajax form. It all works fine except that if you press enter rather than the submit button it does not work. I've tried adding onsubmit to the form but that doesn't have an effect. Probably something really simple that i am missing so would appreciate any advice/help. read quite a few forum answers but hasn't helped me that much as i don't understand much javascript and can't really see what is wrong.

    here is the code i have -

    Code:
    <html>
    <head>
    
     <script language="javascript" type="text/javascript">
    <!-- 
    //Browser Support Code
    function ajaxFunction(){
    	var ajaxRequest;  // The variable that makes Ajax possible!
    	
    	try{
    		// Opera 8.0+, Firefox, Safari
    		ajaxRequest = new XMLHttpRequest();
    	} catch (e){
    		// Internet Explorer Browsers
    		try{
    			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    		} catch (e) {
    			try{
    				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    			} catch (e){
    				// Something went wrong
    				alert("Your browser broke!");
    				return false;
    			}
    		}
    	}
    	// Create a function that will receive data sent from the server
    	ajaxRequest.onreadystatechange = function(){
    		if(ajaxRequest.readyState == 4){
    			var ajaxDisplay = document.getElementById('ajaxDiv');
    			ajaxDisplay.innerHTML = ajaxRequest.responseText;
    		}
    	}
    	var name = document.getElementById('name').value;
    	var type = document.getElementById('type').value;
    	var queryString = "?name=" + name + "&type=" + type;
    	ajaxRequest.open("GET", "feed.php" + queryString, true);
    	ajaxRequest.send(null); 
    }
    
    //-->
    </script>
    
    </head>
    <body>
    <div align="center"> <font face="Arial, Helvetica, sans-serif">
     
      </font>
      <table width="780" border="0" align="center" cellpadding="6" cellspacing="6" bgcolor="#339933">
        <tr> 
          <td colspan="2">
          
          <div id='ajaxDiv'><font face="Arial, Helvetica, sans-serif">
            <form name='myForm' onsubmit='ajaxFunction()'>
              <p><font face="Arial, Helvetica, sans-serif"><strong>Enter full or part 
                of fish name: </strong> 
                <input name="name" type='text' id='name' size="44"/>
                </font></p>
              <p><font face="Arial, Helvetica, sans-serif"><strong>Select name type</strong> 
                <select name="type" id="type" size="1">
                  <option value="com">common</option>
                  <option value="sci">scientific</option>
                </select>
                </font></p>
              <p><font face="Arial, Helvetica, sans-serif"><br />
                <input type='button' value='search'>
                </font></p>
            </form>
            Your result 
              will display here</font></div></td>
        </tr>
      </table>
    </div>
    </body>
    </html>
    thanks
    If i am a product of your imagination you should try harder!

  2. #2
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,096
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    I'm not too sure why the form is behaving like that for you.
    I tried your code out locally. I had to change this:

    HTML Code:
    <input type='button' value='search'>
    into this:

    HTML Code:
    <input type='submit' value='search'>
    and then everything worked as expected, that is to say, the ajaxFunction function was called regardless of how I submitted the form.

    Anyway, there was quite a bit about your markup which could easily lead to your code getting convoluted and making debugging more difficult, so I took the liberty of rewriting it somewhat:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Fish quiz</title>
        <style>
          #container{
            width:780px;;
            margin: 0 auto;
            background: #339933;
            margin-top:5px;
            font-family:Arial, Helvetica, sans-serif;
          }
          
          #myForm{
            padding:25px 15px 5px 15px;
          }
          
          #result{
            padding: 0 0 25px 15px;
          }
          
          #myForm div{
            margin-bottom:15px;
          }
        </style>
      </head>
      
      <body>
        <div id="container">
          <form name='myForm' id="myForm">
            <div>
              <label for="name"><strong>Enter full or part of fish name</strong>: </label>
              <input name="name" type='text' id='name' size="44"/>
            </div>
            <div>
            <label for="type"><strong>Select name type</strong>:</label>
              <select name="type" id="type" size="1">
                <option value="com">common</option>
                <option value="sci">scientific</option>
              </select>
            </div>
            <div>
              <input type='submit' value='search'>
            </div>
          </form>
          
          <div id="result">Your result will display here</div>
        </div>
        
        <script language="javascript" type="text/javascript">
          function ajaxFunction(e){
            console.log("Do some AJAX stuff here");
            
            // Then prevent the form's default action
            e.preventDefault();
          }
          
          var f = document.getElementById("myForm");
          f.onsubmit = ajaxFunction;
        </script>
      </body>
    </html>
    I did the following things:
    1. Added label tags to the form fields
    2. Removed all of the inline markup in favour of CSS at the top of the document
    3. Removed the inline event handler on the form and put this with the rest of the JS

    Hopefully this will give you somewhat of a template to work from. It should also solve the problem of the code not submitting when you press enter.

  3. #3
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Hiding from the world
    Posts
    357
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,
    wow thanks for putting so much effort into the answer. Although i feel bad now as that was just a test which was why all the ugly code was left in and no style sheets etc. It will look a lot better when its in place.

    so still a bit confused as i am not sure how my ajax code fits in in the code you did?

    this is my page working with my code but only when you click the button not when you press enter. http://beta.mcsuk.org/ukseas/
    The event is still onclick on the button. I tried changing it to 'submit' like you put but then it doesn't work at all for some reason.

    if you have time to help a bit more that would be most appreciated.

    thanks
    If i am a product of your imagination you should try harder!

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,096
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    No probs
    I am at work right now, but I don't mind having a look when I get back home.

    In the meantime could you post the contents of feed.php

  5. #5
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Hiding from the world
    Posts
    357
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks so much

    this is the feed page which is php/mysql

    Code:
    <?php
    $dbhost = "localhost";
    $dbuser = "#####";
    $dbpass = "#####";
    $dbname = "###";
    	//Connect to MySQL Server
    mysql_connect($dbhost, $dbuser, $dbpass);
    	//Select Database
    mysql_select_db($dbname) or die(mysql_error());
    	// Retrieve data from Query String
    $name = $_GET['name'];
    $type = $_GET['type'];
    
    
    if($type=='com'){$specify ='name';}
    elseif($type=='sci'){$specify='scientific_name';}
    
    	//build query
    $query = "SELECT * FROM fish WHERE $specify LIKE '%$name%' ";
    
    	//Execute query
    $qry_result = mysql_query($query) or die(mysql_error());
    
    	//Build Result String
    $display_string = '<table cellpadding="5" cellspacing="1">';
    $display_string .= "<tr>";
    $display_string .= "<td><strong>Common name</strong></td>";
    $display_string .= "<td><strong>Scientific name</strong></td>";
    $display_string .= "</tr>";
    
    // Define the colours for the alternating rows 
        $colour_odd = "#efefef"; 
        $colour_even = "#ECD279"; 
       $row_count = 0;  //To keep track of row number 
    
    
    	// Insert a new row in the table for each person returned
    while($row = mysql_fetch_array($qry_result)){
    
    // Decide which colours to alternate for the rows 
         // If Remainder of $row_count divided by 2 == 0. 
         $row_color = (($row_count % 2) == 0) ? $colour_even : $colour_odd; 
    
    	$display_string .= "<tr bgcolor='" . $row_color . "'>";
    	$display_string .= "<td><a onmouseover='this.style.cursor=\"pointer\" ' onfocus='this.blur();' onclick=\"document.getElementById('PopUp".$row[id]."').style.display = 'block'\">".$row[name]."</a></td>";
    	$display_string .= "<td>".$row[scientific_name]."</td>";
    	$display_string .= "</tr>";
    	$display_string .= "
    			<div id='PopUp".$row[id]."' style='display: none; position: absolute; left: 50px; top: 50px; border: solid black 1px; padding: 10px; background-color: white; text-align: left; font-size: 12px; width: 255px;z-index:100;'>
    			<strong>".$row[name]."</strong>
    			<br> ".$row[summary]."
    			<br />
    			<div style='text-align: right;'>
    			<a onmouseover='this.style.cursor=\"pointer\" ' style='font-size: 12px;' onfocus='this.blur();' onclick=\"document.getElementById('PopUp".$row[id]."').style.display = 'none' \" >
    			<span style=\"text-decoration: underline;\">Close</span></a></div>
    			</div>
    ";
    	
    				
    	// Increment the row count 
         $row_count++; 			
    				
    	
    }
    //echo "<span style='color:#ccc'>'Query: " . $query . "</span><br />";
    $display_string .= "</table>";
    $display_string .= '<p><a href="?">Return</a></p>';
    echo $display_string;
    
    
    
    
    
    ?>
    NB this is only really to test stuff at the moment so again quite messy. My final page won't have popups, i'll just code it to return the entire page instead for each result. Also will be upgrading to mysqli as support for mysql is ending etc.

    thanks
    If i am a product of your imagination you should try harder!

  6. #6
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,096
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Hi there,

    You would combine them like this:

    Code:
    <!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Fish quiz</title>
        <style>
          #container{
            width:780px;;
            margin: 0 auto;
            background: #339933;
            margin-top:5px;
            font-family:Arial, Helvetica, sans-serif;
          }
          
          #myForm{
            padding:25px 15px 5px 15px;
          }
          
          #ajaxDiv{
            padding: 0 0 25px 15px;
          }
          
          #myForm div{
            margin-bottom:15px;
          }
        </style>
      </head>
      
      <body>
        <div id="container">
          <form name='myForm' id="myForm">
            <div>
              <label for="name"><strong>Enter full or part of fish name</strong>: </label>
              <input name="name" type='text' id='name' size="44"/>
            </div>
            <div>
            <label for="type"><strong>Select name type</strong>:</label>
              <select name="type" id="type" size="1">
                <option value="com">common</option>
                <option value="sci">scientific</option>
              </select>
            </div>
            <div>
              <input type='submit' value='search'>
            </div>
          </form>
          
          <div id="ajaxDiv">Your result will display here</div>
        </div>
        
        <script language="javascript" type="text/javascript">
          function ajaxFunction(e){
            e.preventDefault();
            
            var ajaxRequest;  // The variable that makes Ajax possible!
            
            try{
              // Opera 8.0+, Firefox, Safari
              ajaxRequest = new XMLHttpRequest();
            } catch (e){
              // Internet Explorer Browsers
              try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
              } catch (e) {
                try{
                  ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                  // Something went wrong
                  alert("Your browser broke!");
                  return false;
                }
              }
            }
            
            // Create a function that will receive data sent from the server
            ajaxRequest.onreadystatechange = function(){
              if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
              }
            }
            
            var name = document.getElementById('name').value;
            var type = document.getElementById('type').value;
            var queryString = "?name=" + name + "&type=" + type;
            ajaxRequest.open("GET", "feed.php" + queryString, true);
            ajaxRequest.send(null); 
          }
          
          var f = document.getElementById("myForm");
          f.onsubmit = ajaxFunction;
        </script>
      </body>
    </html>
    Here's a demo of everything working.

    As your feed.php file does a database query which I cannot replicate, I shortened my version to just echo back the form values at you.

    feed.php

    PHP Code:
    <?php
      
    echo "You entered: " $_GET['name'] . " and " $_GET['type'];
    ?>
    As you can see from the demo, the form submits when you click "search" or press return.

    I Hope that helps.
    Let me know if you have any questions.

  7. #7
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Hiding from the world
    Posts
    357
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thank you so much that is awesome and exactly what i need. it's all working with the database here http://beta.mcsuk.org/ukseas/ if you search 'cod' or 'tuna' etc if will return the results perfectly.

    So hopefully i am correct in my thinking that the 'e.preventDefault();' part is a standard javascript way of stopping the 'enter' key action.

    then this part
    'var f = document.getElementById("myForm");
    f.onsubmit = ajaxFunction;'

    supersedes the enter key and uses the form submission as a trigger to then run the ajax part

    Hopefully i've learnt something as i hate just asking people to do all the work for me, so i try and learn for next time.


    thanks
    If i am a product of your imagination you should try harder!

  8. #8
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,096
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Howdy,

    Glad that you got everything working well.
    The site is looking good!

    Quote Originally Posted by Noppy View Post
    So hopefully i am correct in my thinking that the 'e.preventDefault();' part is a standard javascript way of stopping the 'enter' key action.
    Kinda.
    It catches and then cancels the form's submit event (triggered by pressing enter in a text box or by clicking the the submit button).
    Once the submit event has been cancelled, you are free to do all kinds of JS wizardry in its place

    Quote Originally Posted by Noppy View Post
    then this part
    'var f = document.getElementById("myForm");
    f.onsubmit = ajaxFunction;'

    supersedes the enter key and uses the form submission as a trigger to then run the ajax part .
    Also kinda.
    You are attaching an event listener to the form, which will call a function when the form is submitted.
    However, if you don't prevent the form's default submit action from within your function, then this will also be exectued.

    Here's an example:

    Imagine you have a form:

    HTML Code:
    <form action="myScript.php" id="myForm">
      <label for="name">Enter your name:</label>
      <input type="text" id="name"/>
      <input type="submit">
    </form>
    and the following JavaScript:

    Code JavaScript:
    f = document.getElementById("myForm");
    f.onsubmit = function (){
      console.log(f.name.value); 
    }

    This code would attach an event listener to the form which would be called when a user submitted the form in any way.
    The code would attempt to output the name entered to the console (see here for short console tutorial).
    However, in addition to running this code, the browser would also follow the link to myScript.php, so effectively you would see the output for a split second, then the browser would navigate away from the page.

    By passing a reference to the submit event to our event listener, we can also prevent this behaviour:

    Code JavaScript:
    f = document.getElementById("myForm");
    f.onsubmit = function (e){
      e.preventDefault();
      console.log(f.name.value); 
    }

    Now, when a user submits the form, the browser no longer follows the link in the form's action attribute and logs the output to the console as desired.

    I hope that makes sense.

  9. #9
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    6,096
    Mentioned
    219 Post(s)
    Tagged
    12 Thread(s)
    Also, as you are doing this with AJAX, I have a suggestion for your page.

    Would it not make more sense to load the search results into a div beneath the search box.
    Currently you are overwriting the search box, so that if I don't know what I am searching for, I have to refresh the page to refine my search.

    Just a suggestion and it would be easy to implement.

  10. #10
    SitePoint Addict
    Join Date
    Jan 2005
    Location
    Hiding from the world
    Posts
    357
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    cool thanks thats really useful info and will hopefully come mean i can get a bit further next time before having to ask for help

    Yeah you are probably right on leaving the form visible. Eventually i will be adding an extra tier to the ajax so that you submit - get the list - choose a fish and submit - get a detailed page about that fish.

    at the moment i am just returning a simple popup to test but will be better returning a new fresh page as it'll mean less code returned for the first part of the search. If that all makes sense.



    glad you like the site. It's going live in the next few weeks just finishing a few bits off


    Thanks again for spending your time helping me on this and for explaining things so well. Hopefully someone else might find this useful as well
    If i am a product of your imagination you should try harder!


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
  •