Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    Regular Coder adarshakb's Avatar
    Join Date
    Jun 2009
    Location
    Silicon valley of india
    Posts
    247
    Thanks
    11
    Thanked 1 Time in 1 Post

    Post Simple AJAX request

    hi,
    I had a doubt... here is a simple ajax program to return the length of the string entered in the input
    html:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type='text/javascript' src="grade.js" > </script>
    <title>Untitled Document</title>
    </head>
    
    <body>
    <form action="fallbackpage.php" method="post">
    	 
    	 
    	 
    	 <p>Welcome, student. Please enter your essay here:</p>
      <p>
    	   <textarea name="essay" id="essay">
    	 
    	 </textarea>
      </p>
    	 <p>
    	   <input type="submit" name="submit" value="Submit" onclick="
           grade(this.form.essay.value);" />
    	 </p>
    	 
    </form>
    </body>
    </html>
    Java script
    Code:
    // JavaScript Document
    function grade(essay) {
    
    	// Mozilla version
    
    	if (window.XMLHttpRequest) {
    
    		xhr = new XMLHttpRequest();
    
    	}
    
    	// IE version
    
    	else if (window.ActiveXObject) {
    
    		xhr = new ActiveXObject("Microsoft.XMLHTTP");
    
    	}
    
    	essay=encodeURIComponent(essay);
    
    	xhr.open("POST","grade.php");
    
    	xhr.setRequestHeader(
    
    		'Content-Type',
    
    		'application/x-www-form-urlencoded; charset=UTF-8');
    
    	xhr.send(essay);
    
    	xhr.onreadystatechange=function() {
    
    		if (xhr.readyState==4) {
    
    			grade = xhr.responseText;
    
    
    			alert(grade);
    
    		}
    
    	}
    
    }
    php:
    PHP Code:
    <?php
         
        
    function grade_essay($essay) {
         
             return 
    strlen($essay);
         
        }
         
        
    $essay urldecode(implode(file('php://input')));
         
        
    $grade grade_essay($essay);
         
        echo 
    $grade;
         
        
    ?>
    I just use an alert box to alert the length.

    The script works properly ONLY when the AJAX request is able to outrace the submit request.... which doesnt happen.

    I have included the action="" part as a fallback option incase JS is disabled

    What am i doing wrong here? I am learning JS now in the free time...

    Also i did notice this...
    when i change the submit button in html to the following code i get 2 alert box..1st one's undefined(i know why) but second one's i will get proper answer
    <input type="submit" name="submit" value="Submit" onclick="alert(grade(this.form.essay.value));" />


    PS: This is a tutorial here http://www.webmonkey.com/2010/02/aja...ners/#more-775
    Last edited by adarshakb; 12-13-2010 at 12:04 PM.
    Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.

    Albert Einstein
    -----------------------------------------------------
    My Blog songs

  • #2
    Regular Coder Stooshie's Avatar
    Join Date
    Mar 2008
    Location
    Dundee, Scotland
    Posts
    380
    Thanks
    9
    Thanked 39 Times in 39 Posts
    Make the submit button of type "button" rather than "submit" and you won't have to worry about the automatic redirect as you can then use javascript to submit the form once you have received the ajax response.
    Regards, Stooshie
    O

  • #3
    Regular Coder adarshakb's Avatar
    Join Date
    Jun 2009
    Location
    Silicon valley of india
    Posts
    247
    Thanks
    11
    Thanked 1 Time in 1 Post
    Make the submit button of type "button" rather than "submit" and you won't have to worry about the automatic redirect as you can then use javascript to submit the form once you have received the ajax response.
    when JS is disabled in the client how will a AJAx script work or even a manual JS submission ... i am confused
    Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.

    Albert Einstein
    -----------------------------------------------------
    My Blog songs

  • #4
    Regular Coder Stooshie's Avatar
    Join Date
    Mar 2008
    Location
    Dundee, Scotland
    Posts
    380
    Thanks
    9
    Thanked 39 Times in 39 Posts
    Javascript needs to enabled to allow JavaScript to work. That is the "J" in AJaX. (Asynchronous Javascript and XML).
    Regards, Stooshie
    O

  • #5
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Quote Originally Posted by Stooshie View Post
    Javascript needs to enabled to allow JavaScript to work. That is the "J" in AJaX. (Asynchronous Javascript and XML).
    Yes but if the user turns javascript off then the ajax wont work so if the form submit button is changed to a button the form wont submit if the user turns javascript off, what i would suggest is to keep the form button as type="submit" and then add onsubmit="return false;" so when javascript is on the form will never submit but if javascript is turned off then the form will act as a standard html form.

    EXAMPLE:
    Code:
    <form method="post" action="" onsubmit="return false;">
      <input type="submit" value="Submit" />
    </form>
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #6
    Regular Coder Stooshie's Avatar
    Join Date
    Mar 2008
    Location
    Dundee, Scotland
    Posts
    380
    Thanks
    9
    Thanked 39 Times in 39 Posts
    Quote Originally Posted by DJCMBear View Post
    Yes but if the user turns javascript off then the ajax wont work so if the form submit button is changed to a button the form wont submit if the user turns javascript off, what i would suggest is to keep the form button as type="submit" and then add onsubmit="return false;" so when javascript is on the form will never submit but if javascript is turned off then the form will act as a standard html form.

    EXAMPLE:
    Code:
    <form method="post" action="" onsubmit="return false;">
      <input type="submit" value="Submit" />
    </form>
    I understand that, but the AjAX model of user interaction is completely different to the non-AjAX model. On a simple form like this, you can get away with that but it becomes much more complicated if there is more than one area of the page that can update independently.
    Regards, Stooshie
    O

  • #7
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Quote Originally Posted by Stooshie View Post
    I understand that, but the AjAX model of user interaction is completely different to the non-AjAX model. On a simple form like this, you can get away with that but it becomes much more complicated if there is more than one area of the page that can update independently.
    Not if coding is easy to the coder. Basicly your saying that if you want to update lets say 3 - 4 different things on one page with ajax requests that it is a very hard thing to code, if im honest, it's not that hard it is just like any normal javascript code apart from obtaining the ajax response text and then replacing the old information with the new updated information, and yes you need to know about dom etc but that is all standard javascript "non-AJAX" coding, the only AJAX that is needed is the whole sending and receiving of the different information requests.

    Here is an example of 3 updates on 1 button click.

    - UpdateInfo.js
    Code:
      (function($){
        /**
         * @Function: AJAX :: PUBLIC
         * This opens the AJAX for usage
         */
        $.AJAX = function() {
          var xmlhttp;
          if(window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
          } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
          return xmlhttp;
        };
    
        /**
         * @Object :: Updates :: PUBLIC
         * This holds all page updates
         */
        $.Updates = {
          URL: "http://www.example.com/",
          NameID: "AJAX_UPDATE_NAME",
          AgeID: "AJAX_UPDATE_AGE",
          GenderID: "AJAX_UPDATE_GENDER",
          loadNewName: function(o) {
            var AJAX = new $.AJAX(),
                Current = document.getElementById($.Updates.NameID);
            AJAX.onreadystatechange=function() {
              if(AJAX.readyState==4 && AJAX.status==200) {
                Current.innerHTML = AJAX.responseText;
              }
            };
            AJAX.open("POST",$.Updates.URL+"AJAX.php",true);
            AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            AJAX.send('type=name&ID='+o);
            return this;
          },
          loadNewAge: function(o) {
            var AJAX = new $.AJAX(),
                Current = document.getElementById($.Updates.AgeID);
            AJAX.onreadystatechange=function() {
              if(AJAX.readyState==4 && AJAX.status==200) {
                Current.innerHTML = AJAX.responseText;
              }
            };
            AJAX.open("POST",$.Updates.URL+"AJAX.php",true);
            AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            AJAX.send('type=age&ID='+o);
            return this;
          },
          loadNewGender: function(o) {
            var AJAX = new $.AJAX(),
                Current = document.getElementById($.Updates.GenderID);
            AJAX.onreadystatechange=function() {
              if(AJAX.readyState==4 && AJAX.status==200) {
                Current.innerHTML = AJAX.responseText;
              }
            };
            AJAX.open("POST",$.Updates.URL+"AJAX.php",true);
            AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            AJAX.send('type=gender&ID='+o);
            return this;
          }
        };
    
        /**
         * @Function: UpdateAll :: PUBLIC
         * This will update all member unformation
         */
        $.UpdateAll = function(o) {
          $.Updates.loadNewName(o).loadNewAge(o).loadNewGender(o);
        };
      })(window);
    - Info.html
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
      <title>3 AJAX updates on one page</title>
      <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
      <meta name="keywords" content="" /> 
      <meta name="description" content="" />
      <script src="UpdateInfo.js" type="text/javascript"></script>
    </head>
    <body>
    <input type="button" value="John Doe" onclick="UpdateAll(1);" />
    <input type="button" value="Jane Doe" onclick="UpdateAll(2);" />
    <br />
    Name: <span id="AJAX_UPDATE_NAME">John Doe</span><br />
    Age: <span id="AJAX_UPDATE_AGE">25</span><br />
    Gender: <span id="AJAX_UPDATE_GENDER">Male</span>
    </body>
    </html>
    - AJAX.php
    PHP Code:
    <?php
    if(isset($_POST['type'])) {
      if(
    $_POST['type'] == "name") {
        if(
    $_POST['ID'] == 1) {
          print 
    "John Doe";
        } else {
          print 
    "Jane Doe";
        }
      } elseif(
    $_POST['type'] == "age") {
        if(
    $_POST['ID'] == 1) {
          print 
    25;
        } else {
          print 
    20;
        }
      } elseif(
    $_POST['type'] == "gender") {
        if(
    $_POST['ID'] == 1) {
          print 
    "Male";
        } else {
          print 
    "Female";
        }
      }
    }
    ?>
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • #8
    Regular Coder Stooshie's Avatar
    Join Date
    Mar 2008
    Location
    Dundee, Scotland
    Posts
    380
    Thanks
    9
    Thanked 39 Times in 39 Posts
    Yes, but when I said the Non-Ajax model of interaction I meant how does the user submit and receive data on refresh different parts of the form if they have javascript switched off? Answer is, they can't.

    The model is totally different. For complex ajax pages you have to design the entire page around ajax and then build a series of other forms for users that have js turned off.
    Regards, Stooshie
    O

  • #9
    Senior Coder DJCMBear's Avatar
    Join Date
    Mar 2010
    Location
    United Kindom
    Posts
    1,173
    Thanks
    14
    Thanked 136 Times in 136 Posts
    Quote Originally Posted by Stooshie View Post
    Yes, but when I said the Non-Ajax model of interaction I meant how does the user submit and receive data on refresh different parts of the form if they have javascript switched off? Answer is, they can't.
    To answer this question they can, if it is one form, but if it is lets say 2 or 3 forms you will need to have to store the form information in a server-side session so while the session is active the information being entered into the form will never get lost or removed, and if your asking about a static html site then the answer will be no as there are no server-side codes on the website and javascript is turned off, basicly I would say we are both right in a way as for beginners that are making static html sites they can't submit different forms with-out losing the imputed data on all the forms, then the answer is no it can't be done but for coders that are using server-side codes as well or maybe have the skills to code both html and javascript together to allow the use of the same codes for both types of users the answer would be yes it can be done.

    A form like this is a html stand alone "non-AJAX" form.
    Code:
    <form method="post" action="">
      <input type="text" name="demoinput" />
      <input type="submit" value="Submit" />
    </form>
    A form like this will never be submitted with Javascript turned off, but will be submitted will Javascript turned on.
    Code:
    <form method="post" action="">
      <input type="text" name="demoinput" />
      <input type="button" value="Submit" onclick="return submitForm();" />
    </form>
    But a form that includes both ways, a non-Javascript way and a Javascript way will work with both javascript turned on or off.
    Code:
    <form method="post" action="" onsubmit="return false;">
      <input type="text" name="demoinput" />
      <input type="submit" value="Submit" onclick="return submitForm();" />
    </form>
    The red sections are the Javascript and the blue sections are the non-Javascript, So if the javascript is turned off then only the blue areas are used and if the javascript is turned on then both areas are used.

    This allows the developer to create two types of websites one would be for users with javascript turned on and the other for users with javascript turned off, sites such as facebook are highly AJAX coded but if you turn javascript off while on facebook all animations don't happen as there is no javascript allowing it to so you refresh the page and the updates are displayed as it is stand alone html and css codes, when on firefox if you click a link in facebook you get the AJAX #!/ in the url where if you turn javascript off you don't get that instead you go to the link like any non-Javascript link. These are ways of coding that very advanced developers have learnt how to do so you can give users with javascript turned on a better way to use the website.

    Quote Originally Posted by Stooshie View Post
    The model is totally different. For complex ajax pages you have to design the entire page around ajax and then build a series of other forms for users that have js turned off.
    If you are an advanced web developer you can create html forms that can do both ways so you only need to have one form for both javascript users and non-Javascript users like the form above, where the blue codes are standard html codes which non-Javascript users will have use of and the blue and red sections of the html code are for Javascript users, the red onsubmit will return false meaning if a Javascript user submits the form like a non-Javascript user would then do NOT submit the form and the red onclick code will say if the Javascript user clicks this button then run this function which if the function submits the form then the form will be submitted or if the function uses ajax to do the updates with no form submit and no page reloads then the Javascript user will not have to wait for a reload to submit the information from the form to the server-side codes.
    Official BinPress hand picked coder.
    For anyone worried about SQL injection go have a look at my small yet powerful script here.
    Go Pledge for Light Table, if it hit's $300,000 Python and other languages will get added.
    I am 1 of 65,608 people to get a Pebble Watch :P

  • Users who have thanked DJCMBear for this post:

    adarshakb (12-24-2010)

  • #10
    Regular Coder Stooshie's Avatar
    Join Date
    Mar 2008
    Location
    Dundee, Scotland
    Posts
    380
    Thanks
    9
    Thanked 39 Times in 39 Posts
    Sorry, in your form that works for javascript and non-javascript users, to where is the data submitted if the user has javascript turned off?
    Regards, Stooshie
    O


  •  

    Posting Permissions

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