Ajax Question

Discussion in 'Programming' started by TechBoyJK, Sep 14, 2012.

  1. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    Ajax question...

    I'm working on trying to get my mind around how to properly develop ajax functionality.

    I've been able to write a basic ajax script which basically takes the input in a form field, and 'onBlur' will send that input to a remote function I built. The results are returned via JSON, and I've written the ajax script to responding accordingly based upon the results.

    However, I'm not sure how to expand this script beyond one function without having to replicate the entire set of ajax functions required to make it work.

    I have 3 functions declared in the script

    ProcessXML // opens XMLhttpRequest > data contained in variable 'obj'
    ProcessChange //checks readyState of 'obj'
    checkRedirectExists // custom function that calls remote function and returns json data.

    CheckRedirectExists > ProcessXML > Process Change

    The way I've been able to get my ajax script to work has forced me to write ProcessChange to be specific to my 'checkRedirectExists' function. I want to write another function, but I can't use the ProcessXML and ProcessChange functions because ProcessChange is coded to expect and act on results generated from the checkRedirectExists function.

    Do I need a seperate ProcessXML/ProcessChange function for each custom function I write?

    Once I get the proper method to make this work, I'll probably end up with a dozen javascript functions in a single document. I'm trying to avoid having to write specific XMLhttpRequest calls for each function.

    Another thing that's leading me to think that I need specific ProcessXML and Process Change functions for each custom ajax function I write is "what if I have several functions fire at once? They'd all be trying to use the same XMLHTTPRequest results.

    Big Question, do I need to duplicate this entire script for each ajax function?

    Code:
    
    <script>
    	
    	var obj;
    
    	function ProcessXML(url) {
    	  // native  object
    
    	  if (window.XMLHttpRequest) {
    	    // obtain new object
    	    obj = new XMLHttpRequest();
    	    // set the callback function
    	    obj.onreadystatechange = processChange;
    	    // we will do a GET with the url; "true" for asynch
    	    obj.open("GET", url, true);
    	    // null for GET with native object
    	    obj.send(null);
    	  // IE/Windows ActiveX object
    	  } else if (window.ActiveXObject) {
    	    obj = new ActiveXObject("Microsoft.XMLHTTP");
    	    if (obj) {
    	      obj.onreadystatechange = processChange;
    	      obj.open("GET", url, true);
    	      // don't send null for ActiveX
    	      obj.send();
    	    }
    	  } else {
    	    alert("Your browser does not support AJAX");
    	  }
    	}
    
    
    	function processChange() {
        // 4 means the response has been returned and ready to be processed
        if (obj.readyState == 4) {
            // 200 means "OK"
            if (obj.status == 200) {
    			mpInfo = eval("(" + obj.responseText + ")");
    			if (mpInfo.error == 1){
    			alert(obj.responseText);
    			document.getElementById("button").disabled = true;
    			}
    			else if (mpInfo.error == 0){
    			document.getElementById("button").disabled = false;
    			}
    			
            } else if (obj.status == 404){
                alert("whoa... 404!");
        	    	}
    	    	}
    		}
    		
    		
    			
    	function checkRedirectExists(input, response) {
    	  // if response is not empty, we have received data back from the server
    	  if (response != '') {
    	    // the value of response is returned from checkName.php: 1 means in use
    	    if (response == '1') {} 
    		else {
    	    //  if response is empty, we need to send the username to the server
    
    	       url  =  "http://details.at/config/cfc/dns.cfc?method=dnsQuickCheck&domain=details.at&subFolder="+ input;
    	       ProcessXML(url);
    		    }
    		  }
    		}
    
    </script>
    
    
     
  2. sourceninja

    sourceninja Diamond Member

    Joined:
    Mar 8, 2005
    Messages:
    8,586
    Likes Received:
    4
    Is there a reason you want to do this the hard way instead of using tools like jquery or prototype?
     
  3. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    Well.... my functions are specific to my app. There's some jquery stuff I'm using, but not for this.

    Regardless, I'm trying to wrap my mind around the proper way to do this without any external libraries.
     
  4. IHateMyJob2004

    Joined:
    Sep 29, 2004
    Messages:
    17,699
    Likes Received:
    1
    or YUI 3?

    Knowing the guts of AJAX (what the OP is using) is a good study. But in the real world you would never use it directly.

    So, curiosity/homework: Use AJAX directly
    Actual real world application: YUI 3

    Sorry, I like my YUI ;-)
     
  5. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    That's thing. I want to KNOW how this all works. I want to write a few different functions that can all send XMLHTTPrequests and parse the results. With the way I have it written now, only one function can use the xmlhttprequest functions unless I write an XMLhttprequest function for each custom function....
     
  6. Dratickon

    Dratickon Junior Member

    Joined:
    May 13, 2012
    Messages:
    21
    Likes Received:
    0
    I don't think I fully understand your question, or at least what the problem is. At what point do you want to call different functions and what other functions are you planning to implement? I don't see why you couldn't tweak those functions to be reusable, but I guess it really depends on what other things you're looking to do. Are you looking to build different URLs to pass into processXML() and then process the responses in different ways through processChange() depending on what URL was originally built/passed in?

    Sorry if I completely missed something! :|
     
  7. Leros

    Leros Lifer

    Joined:
    Jul 11, 2004
    Messages:
    21,881
    Likes Received:
    5
    You need to take a step back and figure out how to wrap your core ajax functionality into a single generic function that you can use for all of your requests.
     
  8. beginner99

    beginner99 Platinum Member

    Joined:
    Jun 2, 2009
    Messages:
    2,832
    Likes Received:
    4
    which would be re-inventing existing libraries.

    i see the point of the OP of wanting to understanding whats behind it but were is the limit? There is also something behind basic javascript (eg which implementation/browser) and so on. You can't understand everything down to the hardware so why not just stop at the level used in practice?
     
  9. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    Let's say I have a function called 'createUser'. That function sends a bunch of parameters to a URL, and gets a json response back. How 'processChange' reacts is currently dependant on the JSON results returned from a different function.

    My thoughts were to instead user a different processChange function written specifically for the 'createUser' function and probably instead call 'processChange' 'processCreateUser'.

    Now, the downside to this is that then my ProcessXML script won't work, as it specifically calls 'processChange'. So I'd ALSO have to have a specific ProcessXML script as well...
     
  10. Leros

    Leros Lifer

    Joined:
    Jul 11, 2004
    Messages:
    21,881
    Likes Received:
    5
    Write a function that takes a URL, performs the request, and returns JSON. You can use this for all your ajax requests.

    Or better yet, write a function that takes a URL and a callback function. The callback function handles the returned JSON.
     
  11. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,687
    Likes Received:
    8
    The processChange method you refer to is the one that needs to know the contents of what comes back from the request in order to do it's job. That's the non-generic piece. The methods that bundle up the parameters, execute the request, handle any errors, and return the raw result can all be generic. I wouldn't get too wrapped up in trying to abstract the code that actually processes those results unless you see some strong common patterns emerging.
     
  12. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    Is there a way to determine the name of the function that initiated the request? In my OP, I had two potential custom functions.

    Would it be reasonable then, in my processChange method to just code it like

    Code:
    	function processChange() {
        // 4 means the response has been returned and ready to be processed
        if (obj.readyState == 4) {
            // 200 means "OK"
            if (obj.status == 200) {
    		if (function == myFunction1) {expect certain data and react accordingly}
    		if (function == myFunction2) {expect certain data and react accordingly}
            } else if (obj.status == 404){
                alert("whoa... 404!");
        	    	}
    	    	}
    		}
    
    Key code is


    if (obj.status == 200) {
    if (function == myFunction1) {expect certain data and react accordingly}
    if (function == myFunction2) {expect certain data and react accordingly}

    #obviously I'm not sure how to declare the function that was being used at that point...
     
  13. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,687
    Likes Received:
    8
    I wouldn't take that approach simply because that function will continue to grow in complexity if you add additional object types. However you could have a "dispatch" function that takes the raw result and looks at it in just enough detail to know what specific processing function to pass it to.
     
  14. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    How would I be able to tell it what function made the request?
     
  15. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,687
    Likes Received:
    8
    You'd need something included in the returned result that provided enough information to determine what was being updated, and what function to call to process the update.
     
  16. cytg111

    cytg111 Platinum Member

    Joined:
    Mar 17, 2008
    Messages:
    2,232
    Likes Received:
    14
    "I'm working on trying to get my mind around how to properly develop ajax functionality. "

    - And i'm the old fart that says it cant be done. Properly, that is. Still waiting for this "everything must run in the (web2.0) browser to be good and true" to pass.
     
  17. TechBoyJK

    TechBoyJK Lifer

    Joined:
    Oct 17, 2002
    Messages:
    16,275
    Likes Received:
    5
    Ok guys, I'm still going to try and learn this, but for the sake of getting a small project done for a demo, I'm going to use jQuery. I'm seeing a lot of tutorials on how to use it, but they all vary a bit so I'm wondering if someone can show me how to do something really basic, because I think I'll be able to put 2 and 2 together after I see it work.

    1. I'm going to use the jQuery set on Google's CND
    Code:
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    2. I'm going to have a text field that 'onblur' will send the data via ajax to a remote function, and (for now) do a simple js popup alert based on the jSON results.

    Code:
    <input id="subFolder" name="subFolder" type="text" onblur="checkRedirectExists(this.value)">
    3. I've written a javaScript function to capture the data and send it to the remote function.

    Code:
    	<script type="text/javascript">function createRedirect(domain, subFolder, redirectUrl, response) {
    	  // if response is not empty, we have received data back from the server
    	  if (response != '') {
    	    // the value of response is returned from checkName.php: 1 means in use
    	    if (response == '1') {} 
    		else {
    	    //  if response is empty, we need to send the username to the server
    
    	       url  =  "http://details.at/config/cfc/dnsCreate.cfc?method=dnsCreate&domain=details.at&subFolder=" +subFolder+"&redirectUrl="+ encodeURI(redirectUrl);
    	       ProcessXML(url);
    		    }
    		  }
    		</script>
    
    

    Anybody feel like showing me what else I need to do to link this alltogether?
     
  18. Markbnj

    Markbnj Elite Member <br>Moderator Emeritus
    Moderator

    Joined:
    Sep 16, 2005
    Messages:
    15,687
    Likes Received:
    8
    It has it's places, but I would agree that it's way overused. I'm on a project now where we have ajax calls going out to retrieve content where the content being returned is 90% or more of the containing page. What's the benefit over just GETting the page from the server? Damned if I know.
     
  19. DannyBoy

    DannyBoy Diamond Member

    Joined:
    Nov 27, 2002
    Messages:
    8,813
    Likes Received:
    0
    jQuery is not javascript.

    Discouraging people from learning how to do something natively, without helpers, isn't good.

    sourceninja - I commend you for wanting to learn the language / API natively.
     
  20. sourceninja

    sourceninja Diamond Member

    Joined:
    Mar 8, 2005
    Messages:
    8,586
    Likes Received:
    4
    Never was discouraging someone from wanting to learn. I was simply asking? Because if your doing it the long/hard way when you have tools to get your job done quickly and efficiently, you should use them.

    Learning is different than getting a job done.
     
  21. DannyBoy

    DannyBoy Diamond Member

    Joined:
    Nov 27, 2002
    Messages:
    8,813
    Likes Received:
    0
    Sorry I wasn't having a pop at you :)

    What I was trying to get was that having the tools to get a job done easier doesn't necessarily mean it will be a good job, be done efficiently or even quickly for that matter, not only that but that knowledge will be beneficial when using say, another library.

    When taking shortcuts like using a jQuery helper for something you won't be prepared with the underlying knowledge / understanding of what's going on under the hood, so if you encounter an issue in trying to get something to work you'll often spend longer reading proprietary API docs and discussions / threads that won't necessarily give you the answer you're looking for straight away and will only educate you on one library.

    On the flip side, if you know the more native / low level approach to how something is achieved you'll have a better indication of how to diagnose / debug a particular error when you understand what's likely causing it at a native level, understanding the flow / pseudo code for a piece of code is crucial.

    I'm not averse to jQuery at all, on the contrary I use it daily when it's the right tool for the job to provide minor rapid enhancements to certain sites, but then I come from a lower level background with the knowledge and education of how things work at a native level.

    jQuery's alright in perfect circumstances when everything works, but it's biggest flaw that makes me cringe is the impracticality of debugging the library or any markup dependent on its selectors, it's whole design pattern makes it a nightmare due to the closure based nature of the library.

    2 cents' :)
     
  22. beginner99

    beginner99 Platinum Member

    Joined:
    Jun 2, 2009
    Messages:
    2,832
    Likes Received:
    4
    Yeah true. I created my own Java API and then when I switched to .net I already knew how to create a efficient linked list in .net due to my previous experience. But then felt I still didn't know enough native, low level stuff so I rolled my own JVM, in assembler. /sarcasm

    As in my previous post in this thread, up to which level of abstractions should anyone know about? I mean it is called abstraction so that you don't see or deal with the underlying complexity. And hence not needing to deal with it gives you more time to worry about things that matter like what users actually want and usability and so on...
     
  23. clamum

    clamum Lifer

    Joined:
    Feb 13, 2003
    Messages:
    23,691
    Likes Received:
    6
    My two cents, I'd just use jQuery for the project and learn basic AJAX on my own time. When it comes to work, I try and keep things as quick and simple as possible.
     
Loading...