Go Back   AnandTech Forums > Software > Programming

Forums
· Hardware and Technology
· CPUs and Overclocking
· Motherboards
· Video Cards and Graphics
· Memory and Storage
· Power Supplies
· Cases & Cooling
· SFF, Notebooks, Pre-Built/Barebones PCs
· Networking
· Peripherals
· General Hardware
· Highly Technical
· Computer Help
· Home Theater PCs
· Consumer Electronics
· Digital and Video Cameras
· Mobile Devices & Gadgets
· Audio/Video & Home Theater
· Software
· Software for Windows
· All Things Apple
· *nix Software
· Operating Systems
· Programming
· PC Gaming
· Console Gaming
· Distributed Computing
· Security
· Social
· Off Topic
· Politics and News
· Discussion Club
· Love and Relationships
· The Garage
· Health and Fitness
· Merchandise and Shopping
· For Sale/Trade
· Hot Deals with Free Stuff/Contests
· Black Friday 2013
· Forum Issues
· Technical Forum Issues
· Personal Forum Issues
· Suggestion Box
· Moderator Resources
· Moderator Discussions
   

Reply
 
Thread Tools
Old 09-14-2012, 03:05 PM   #1
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default Ajax Question

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>
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-14-2012, 03:13 PM   #2
sourceninja
Diamond Member
 
sourceninja's Avatar
 
Join Date: Mar 2005
Posts: 7,867
Default

Is there a reason you want to do this the hard way instead of using tools like jquery or prototype?
sourceninja is offline   Reply With Quote
Old 09-14-2012, 03:28 PM   #3
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

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.
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-14-2012, 03:29 PM   #4
IHateMyJob2004
Lifer
 
IHateMyJob2004's Avatar
 
Join Date: Sep 2004
Posts: 15,822
Default

Quote:
Originally Posted by sourceninja View Post
Is there a reason you want to do this the hard way instead of using tools like jquery or prototype?
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 ;-)
__________________
Look at the Blackberry Z10 with an open mind. It is actually good!
FREE MUSIC - via torrent:
http://bt.etree.org/
or just download some free music:
http://www.archive.org/audio/etree-band-showall.php 100% LEGIT!
IHateMyJob2004 is offline   Reply With Quote
Old 09-14-2012, 03:36 PM   #5
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

Quote:
Originally Posted by IHateMyJob2004 View Post
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 ;-)
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....
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-14-2012, 09:48 PM   #6
Dratickon
Junior Member
 
Join Date: May 2012
Posts: 21
Default

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!
Dratickon is offline   Reply With Quote
Old 09-14-2012, 11:48 PM   #7
Leros
Lifer
 
Leros's Avatar
 
Join Date: Jul 2004
Location: Austin, TX
Posts: 21,369
Default

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.
Leros is offline   Reply With Quote
Old 09-15-2012, 08:27 AM   #8
beginner99
Platinum Member
 
Join Date: Jun 2009
Posts: 2,121
Default

Quote:
Originally Posted by Leros View Post
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.
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?
beginner99 is offline   Reply With Quote
Old 09-15-2012, 11:31 AM   #9
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

Quote:
Originally Posted by Dratickon View Post
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!
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...
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-15-2012, 11:42 AM   #10
Leros
Lifer
 
Leros's Avatar
 
Join Date: Jul 2004
Location: Austin, TX
Posts: 21,369
Default

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.
Leros is offline   Reply With Quote
Old 09-15-2012, 11:45 AM   #11
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 11,712
Default

Quote:
Originally Posted by TechBoyJK View Post
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...
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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is online now   Reply With Quote
Old 09-15-2012, 12:52 PM   #12
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

Quote:
Originally Posted by Markbnj View Post
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.
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...
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-15-2012, 07:58 PM   #13
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 11,712
Default

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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is online now   Reply With Quote
Old 09-17-2012, 10:39 AM   #14
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

How would I be able to tell it what function made the request?
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-17-2012, 12:48 PM   #15
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 11,712
Default

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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is online now   Reply With Quote
Old 09-17-2012, 01:42 PM   #16
cytg111
Golden Member
 
Join Date: Mar 2008
Posts: 1,279
Default

"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.
__________________
404
cytg111 is offline   Reply With Quote
Old 09-17-2012, 01:43 PM   #17
TechBoyJK
Lifer
 
TechBoyJK's Avatar
 
Join Date: Oct 2002
Posts: 13,315
Default

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?
__________________
Originally posted by: n0cmonkey
You're being difficult. You have not provided us with the information we need to troubleshoot the problem. You have not given us errors, you're vague about where the problem is, you are not answering the questions we ask. In short, you DON'T KNOW HOW TO THINK. Give back that piece of paper you think makes your intelligent, apologize, destroy your computer and go live in the woods kid.
TechBoyJK is offline   Reply With Quote
Old 09-17-2012, 03:43 PM   #18
Markbnj
Moderator
Programming
 
Markbnj's Avatar
 
Join Date: Sep 2005
Posts: 11,712
Default

Quote:
Originally Posted by cytg111 View Post
"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.
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.
__________________
Everytime I try to tell you, the words just come out wrong

**
Some meaningless scribbling of no account

The 4th Realm

Arts and Letters Daily - Get some culture
Markbnj is online now   Reply With Quote
Old 11-05-2012, 09:00 AM   #19
DannyBoy
Diamond Member
 
DannyBoy's Avatar
 
Join Date: Nov 2002
Location: London, UK
Posts: 8,757
Default

Quote:
Originally Posted by sourceninja View Post
Is there a reason you want to do this the hard way instead of using tools like jquery or prototype?
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.
__________________
DannyBoy is offline   Reply With Quote
Old 11-05-2012, 12:02 PM   #20
sourceninja
Diamond Member
 
sourceninja's Avatar
 
Join Date: Mar 2005
Posts: 7,867
Default

Quote:
Originally Posted by DannyBoy View Post
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.
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.
sourceninja is offline   Reply With Quote
Old 11-05-2012, 01:30 PM   #21
DannyBoy
Diamond Member
 
DannyBoy's Avatar
 
Join Date: Nov 2002
Location: London, UK
Posts: 8,757
Default

Quote:
Originally Posted by sourceninja View Post
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.
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'
__________________
DannyBoy is offline   Reply With Quote
Old 11-05-2012, 02:32 PM   #22
beginner99
Platinum Member
 
Join Date: Jun 2009
Posts: 2,121
Default

Quote:
Originally Posted by DannyBoy View Post
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'
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...
beginner99 is offline   Reply With Quote
Old 11-06-2012, 12:43 PM   #23
clamum
Lifer
 
clamum's Avatar
 
Join Date: Feb 2003
Posts: 21,481
Default

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.
__________________
\ Battlefield 4 Stats /\ Heat /
clamum is online now   Reply With Quote
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -5. The time now is 08:22 PM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.