SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist
    Join Date
    Jul 2004
    Location
    USA
    Posts
    594
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Submit Form with Ajax

    Hello All,

    I'm trying to submit a comment form through AJAX, like Facebook does with there Wall application.

    This is the Javascript im using:
    Code:
    <script language="Javascript">
    function newComment(){
    	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("You need to upgrade your browser, please!");
    				return false;
    			}
    		}
    	}
    	// Create a function that will receive data sent from the server
    	ajaxRequest.onreadystatechange = function(){
    		if(ajaxRequest.readyState == 4){
    			document.getElementById('newcom').innerHTML = ajaxRequest.responseText;
    		}
    	}
    	ajaxRequest.open("POST", "http://www.url.com/process/comment.php?aj=1&id=<?php echo $game_cid; ?>", true);
    	ajaxRequest.send(null); 
    }
    
    </script>
    The problem is I cant find out how to change the form to call the function. Im trying this, but its not working (and reloading the page):

    Code:
    <form method="post" onsubmit="new Ajax.Request({ onLoading:newComment(){
    $('submit_button').disable(); } })">
    
                            
    <p>
      <textarea rows="3" name="comment" cols="50"></textarea>
      </p>
      <p>
      <input type="submit" value="Post My Comment" name="B1">
      
      <button id="finalize_button" type="submit" onclick="newComment();
    return true;">AJAX</button>
    
      
      <input type="submit" onsubmit="newComment()" value="Post Ajax Comment" name="B1">
    </p>
    </form>
    Can anyone shed some light on how I can get this to function.

    Thanks
    BKerr

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    with the form onsubmit, you need to either return false from the function, or explicitly return false from the onsubmit to prevent the default behaviour (that of the page reloading) from occuring.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript


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
  •