|
jairez
|
 |
« on: December 15, 2008, 01:28:55 PM » |
|
Or is it really a versus?
I'm finally getting my feet wet in Ajax and need to know if there's a preference to using one of these? Or should/can I use both?
Thoughts? Samples? As alway, I'm very much appreciative of the handholding and insight.
- ja
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
perkiset
|
 |
« Reply #1 on: December 15, 2008, 01:53:10 PM » |
|
I originally passed all information back and forth as XML.
It sucked, especially for big records.
Instead, I either send a REALLY plain text back, something monsterously complicated, like, "OK" or I send back JSON encoded data, which converts into a JS array super fast and easy.
If I have something really complicated I am sending back I am even known to send back completed HTML and simply say that the innerHTML of a node gets <whatever was passed back> from the AJAX call.
What kind of samples are you looking for? What method of AJAXing are you doing? Have you looked at my XMLHTTP wrapper here in the JS/Ajax repository?
|
|
|
|
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
vsloathe
|
 |
« Reply #2 on: December 15, 2008, 01:56:20 PM » |
|
I know I should be json encoding data but I have been base64 encoding it to pass back and forth lol.
|
|
|
|
|
Logged
|
hai
|
|
|
|
perkiset
|
 |
« Reply #3 on: December 15, 2008, 02:18:51 PM » |
|
The fact is that it really doesn't matter from a transmission perspective how you send data to and fro, only from an encoding and decoding load perspective.
I posted a JSON encoder for JS here somewhere as well, because sometimes I want to send just a boatload of data back up to the server - or more interestingly, at development time I don't *know* how many parms will be coming up from the client, so I'll encode as JSON to send up as well, because it's faster than building XML or lotsalotsa functions to add POST parameters to my Ajax requester. JSON is a handy tool to have in the box.
|
|
|
|
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
jairez
|
 |
« Reply #4 on: December 15, 2008, 04:29:38 PM » |
|
Have you looked at my XMLHTTP wrapper here in the JS/Ajax repository? Indeed, I have. I've poured over it like the Zapruder film and wouldn't necessarily classify it as "first AJAX reading" material - but I totally get the gist of where you're going with it. So I thought I'd start off a bit simpler. Here are my code samples ... - "You know it's good shit ... I got it offa' coder!" - Caddy Shack munge <body>
<script language="javascript" type="text/javascript">
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 namelast = document.getElementById("namelast").value ; var queryString = "?thelastname =" + namelast ; ajaxRequest.open("POST", "ajax_example.cfm" + queryString, true); ajaxRequest.send(null); } </script>
<form name="myForm">
Name Last: <input type="text" id="namelast" onChange="ajaxFunction();"/> <br /> </form>
<div id="ajaxDiv"> Your result will display here </div> </body> </html>
Herez my AJAX page - happens to be ColdFusion, but so what ... <!-- action page -->
<cfset xlname = #url.thelastname#>
<cfquery name="q_getJA" datasource="PREDEFSRC"> SELECT firstname, lastname, id FROM myschema.workfolks where lastname like '#xlname#%' </cfquery>
<table> <tr> <th>First Name</th> <th>Last Name</th> <th>ID</th> </tr>
<cfoutput query="q_getJA"> <tr> <td>#firstname#</td> <td>#lastname#</td> <td>#id#</td> </tr> </cfoutput>
</table>
Let's assume for a moment my select returns the following: Rec1 Firstname: Heywood Lastname: Jablowme ID: 1 Rec2 Firstname: Gimme Lastname: Shelter ID: 69 Rec 3 Firstname: Heywood Lastname: Japayme ID: 15 -------------------------------------------------------- So, in a nut sackshell, I'm trying to see what is being passed (object type and values) back to responseText or responseXML in this case. Am I getting a text string with responseText? An XML object with responseXML? Thanks guys. - ja btw - I took out the "company specific" details on the fly, so in all honesty ... I'm not certain the code above will cut/copy/paste/WORK. But I mostly need to know what it returned. thx again.
|
|
|
|
« Last Edit: December 15, 2008, 04:33:52 PM by jairez »
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
serialnoob
|
 |
« Reply #5 on: December 15, 2008, 06:43:46 PM » |
|
As for samples, the best I have seen recently (mind you I might not see much!) comes with the "spry" lib from adobe, which ultimately got me into json. RE json, I am certainly not an expert but I now can see what Perky has been suggesting for a while in terms of speed, load and versatility. 
|
|
|
|
|
Logged
|
Success consists of going from failure to failure without loss of enthusiasm - Winston Churchill
|
|
|
|
perkiset
|
 |
« Reply #6 on: December 15, 2008, 09:23:26 PM » |
|
JA - You will experience difficulties with the XMLHTTPRequest that you'll need to code around, which is why I put together the all-in-one class. Your code is fine as a starter, but I'd humbly suggest that my class might make things a little easier for you, allowing you to get to the meat of your goal, rather than dick about with the intricacies of the requestor. Here is an example of using it: ajaxReq = new ajaxRequestor(); ajaxReq.url = 'ajaxHandler.php'; ajaxReq.postParam('aparam', 'hello'); ajaxReq.postParam('another', 'world'); ajaxReq.onSuccess = handleResponse; ajaxReq.execute();
function handleResponse(sender) { alert(sender.lastResponse); // or HTML Style: document.getElementById('anElement').innerHTML = sender.lastResponse; // or JSON Style: var myArray = eval('(' + sender.lastResponse + ')'); }
In this case, I've created an instance of the requester, set the url at the server (with the handling routines) to 'ajaxHandler.php' - added two POST parameters to the request, set the response handler to a function (this is arguably the most important feature) and sent it off. The handling function receives exactly one parameter - an instance of the object itself. the lastResponse property contains what was sent from the server. My personal desire with the requester was to take the mechanics of AJAX out of the loop as quickly and thoroughly as possible - getting me back to simply generating and handling events. Clearly, I was not satisfied with simply using someone else's class and so I created my own ergo, it is inherently hypocritical for me to suggest that my class would be enough for you. But since the goal of someone like you (as I know you) is much more the business result of an application rather than fascination with the gorgeous efficiency of something you crafted yourself, perhaps this hypocrisy could be overlooked. Note that using this class (as with just about all AJAX methods) the content of the transmission is immaterial - it is brought in and evaluated by you for its ultimate purpose. Just 
|
|
|
|
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
jairez
|
 |
« Reply #7 on: December 15, 2008, 10:57:18 PM » |
|
Ok ... this is good eats! A couple of questions here ... 1. how do the postParams present themselves to ajaxHandler.php? (post vars? gets? array?) 2. how many postParams can I pass? 3. I assume the "sender" parm on handleResponse() is an object ... but where did it come from? 4. the lastResponse item ... I assume that's whatever is passed back from ajaxHandler.php, right? Can it be anything? Is there something that it SHOULD be? 5. do I need to do something to the object when I'm done with it? (thought I read sending a close header somewhere ...) But since the goal of someone like you (as I know you) is much more the business result of an application Oh ... you know me too well  Some would say "it's an edged tool who's historical value to our society knows no bounds, save that of building a civilization." To me, "it's a fuckin' shovel."Thanks, Hoss! - ja
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
jairez
|
 |
« Reply #8 on: December 16, 2008, 10:09:52 AM » |
|
... also, can you post a couple of short ajaxHandler.php examples that pass a) pre-formatted html b) an xml doc c) some type of object (array?)
Sorry to be dense, and while I think I get what's happening here, I just want to be sure.
As ALWAYS ... much grass!
- me
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
perkiset
|
 |
« Reply #9 on: December 16, 2008, 01:12:41 PM » |
|
1. how do the postParams present themselves to ajaxHandler.php? (post vars? gets? array?)
[obj].postParam(name, value) will present as a PHP value in the $_POST array. So, obj.postParam('firstName', 'Perkiset');will show up as $fName = $_POST['firstName']; in PHP. 2. how many postParams can I pass?
I don't know that there's any hard numeric limit. Your server may stop you at a KByte or MByte size though, depending on how Apache and PHP are configured. 3. I assume the "sender" parm on handleResponse() is an object ... but where did it come from?
"sender" is a common parameter name for the object that "sent" the event. In this case, it is the ajaxRequestor itself. This might seem silly and redunant, but consider this: if you had more than one ajaxRequestors instantiated (let's say you were sending several different things concurrently back and forth to the server) and some of them made use of the same handling function, how would you know WHICH request the response is for? This allows the event function to say, "I've received a response and you need to handle it from THIS (sender) object." 4. the lastResponse item ... I assume that's whatever is passed back from ajaxHandler.php, right? Can it be anything? Is there something that it SHOULD be?
That is correct, the lastResponse property on an ajaxRequestor object contains the response we just received. It can be anything from "OK" to runable JavaScript to an encoded JSON string to an XML record to ready-to-display HTML. It should not EVER be completely blank. ALWAYS send at least *something* back from the server. What you send back and forth really depends, again, on the application. Here are a couple thoughts: - If you are sending a simple "update notification" up to the server then just send back OK. You can even do something as simple as this, which is a handy way to handle simple notification ajax calls:
ajaxReq.postParam('fname', 'Perk'); ajaxReq.postParam('lname', 'Iset'); ajaxReq.onSuccess = function(sender) { if (sender.lastResponse != 'OK') alert(sender.lastResponse); } ajaxReq.execute(); ... note how here I do not even "point" to a function, I've created one on the fly in the code. This handler will essentially stay quiet UNLESS there's a problem or the message from the server is NOT "OK".[/li]
- If you are integrating with someone else's code, then XML might be the way to go. There is an XML parser in the Javascript code repository here that I wrote just for that purpose. If you do not have a requirement to go XML, then I'd personally stay away from it, because you add the overhead of creating a record, extra transmission time and the time to parse the record on the client side. It's a bit heavy for this kind of interaction unless it's a requirement.
- You could send back either Javascript or JSON encoded strings to be eval'd at the client. This is a handy way to go particularly if the server might use this ajax call as a redirection or something. So the response could either be a JSON encoded array (which will decode nicely into a JS array) or something like "top.location='/showError.php?message=Youre+Stewed+Butwad';"; in which case the eval'd JS would cause the client to leave the current page and move to another.
- In cases where I want something pretty complicated displayed on the screen, I'll often send read-to-display HTML. Then my code might look something more like this:
ajaxReq.postParam('request', 'retrieveData'); ajaxReq.postParam('type', 'contactRecord'); ajaxReq.postParam('contactID', 12345); ajaxReq.onSuccess = function(sender) { document.getElementById('dataDiv').innerHTML = sender.lastResponse; }
5. do I need to do something to the object when I'm done with it? (thought I read sending a close header somewhere ...)
Nope. As soon as your site moves to another page, garbage collection will be handled and it will disappear. You may reuse it as many times as you want during a single page display. I have complete web applications that are literally, a single web page with a boatload of requestors asking/receiving data like crazy things. It's pretty cool. Hope that helps!
|
|
|
|
« Last Edit: December 16, 2008, 01:15:37 PM by perkiset »
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
perkiset
|
 |
« Reply #10 on: December 16, 2008, 01:39:46 PM » |
|
... also, can you post a couple of short ajaxHandler.php examples that pass a) pre-formatted html b) an xml doc c) some type of object (array?)
Gotta scoot, but this ought to give you some stuff to chew on. Note that I've purposely coded in different idioms with almost every phrase, just so that you can see a few different ways things can be done. Please note also that I typed this directly into the form and have not checked for syntax, but it looks OK. Web page stuff: <html> <head> <style> #resultBox { height: 300px; width: 500px; margin: 0 auto; margin-top: 20px; border-color: black; border-style: solid; border-width: 1px 2px 2px 1px; background-color: #a0a0a0; } #selectType { margin-right: 20px; } </style> </head> <body>
<div style="text-align: center"> <select id="selectType"> <option value="0">Simple Update</option> <option value="1">JSON Array</option> <option value="2">Javascript Redirect</option> <option value="3">Preformatted HTML</option> </select> <input id="testbutton" type="button" value="Test" onClick="test()"> </div>
<div id="resultBox" style=""> </div>
<script> req = new ajaxRequestor(); req.url = '/handler.php';
resArr = new Array();
function test() { var target = document.getElementById('selectType'); var which = target.options[target.selectedIndex].value; req.postParam('request', which); switch(which) { case 0: // This option will hide the test button.. hideButton(); req.onSuccess = function(sender) { showButton(); } break; case 1: // This one too. hideButton(); req.onSuccess = handleJSON; break; case 2: req.onSuccess = function() {}; break; case 3: req.onSuccess = function(sender) { document.getElementById('resultBox').innerHTML = sender.lastResponse; break; } req.execute(); } function hideButton() { document.getElementById('testbutton').style.display = 'none'; } function showButton() { document.getElementById('testbutton').style.display = 'block'; } function handleJSON(sender) { showButton(); try { resArr = eval('(' + sender.lastResponse + ')'); // At this point, resArr now matches the array sent from the PHP handler } catch(e) { alert('Result from server was not valid JSON code. Response was: ' + sender.lastResponse); } } </script> </body></html>
And over at the server, handler.php: <?php $reqType = $_POST['request'] - 0; switch($reqType) { case 0: die('OK'); case 1: $newArr['a'] = 1234; $newArr['b'] = 2345; $newArr['c'] = 3456; $arrStr = json_encode($newArr); echo $arrStr; break; case 2: echo "top.location='www.google.com';"; exit; case 3: echo <<<HTML <center> <h1>Hello World!</h1> <h3>Four score and seven years ago, our fathers brought forth<br> to this country - a new nation - conceived in liberty and dedicated<br> to the proposition that all men are created equal.<br><br>
Or something like that. </h3> HTML; break; }
?>
|
|
|
|
« Last Edit: December 16, 2008, 04:56:52 PM by perkiset »
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
jairez
|
 |
« Reply #11 on: December 16, 2008, 04:05:16 PM » |
|
Dude ... this is freakin' SWEET!  Let me play with this and I'll get back to you on it. Very VERY much appreciated! Thank you! - ja
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
jairez
|
 |
« Reply #12 on: December 16, 2008, 05:22:28 PM » |
|
OK ... I can't get this to work without rem'ing out ... req.onSuccess = function(sender) { document.getElementById('resultBox').innerHTML = sender.lastResponse;
... and then, an alert box comes up saying ... ajaxRequestor successfully returned from a request - but there is no handler assigned to receive it Sorry ... I feel like an ungrateful buzzkill.  Thoughts? Suggestions? Thanks again. - ja
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|
perkiset
|
 |
« Reply #13 on: December 16, 2008, 05:23:42 PM » |
|
I missed the closing curly brace on the end of that line:
req.onSuccess = function(sender) { document.getElementById('resultBox').innerHTML = sender.lastResponse; }
try that lemmee know...
|
|
|
|
|
Logged
|
It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
|
|
|
|
jairez
|
 |
« Reply #14 on: December 16, 2008, 05:54:48 PM » |
|
OMG ... I'm a total gomer for not catching that!  OK ... but I'm still getting the alert box message. I'm wondering if it's the flavor of the library I have? I grabbed the last one posted where you fixed some IE bug. Do I have the right .js file?
|
|
|
|
|
Logged
|
Spontaneity has it's time and place. [Sluggo, 1990-ish]
|
|
|
|