I just need to understand what the following actually does

Okay so I have an existing working Javascript and even a test from an educational lesson video:
Like many callback code I get it the submit button event handler drives the application upon the visitor pressing the submit button it makes the call to the, Hijack method and the callback pulls back the resulting html table code to be placed.

What I do not understand is the line:
     return { Hijack: Hijack, Call: Call };

What exactly am I returning here and what does the notation mean? It looks very JSON
like with the colon so presumably I am returning  the return value of the Hijack method call  as well as the return value of the call method call correct?
why must I return this at all? What is it for?
................
Note also:
I believe that: function(r) {output.innerHTML = r; }
is the key callback method passed into Hijack to render the XmlHTTPRequest response here .
 
Enough said actual code follows assuming a working php service url
See attached codemyscript.js
LVL 2
Robert SilverSr. Software EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gr8gonzoConsultantCommented:
Technically speaking, Lib.Ajax is a function by itself that contains the Hijack and Call functions. So when you run Lib.Ajax by itself, it returns those two functions.

That line exposes the internal functions, so that you can run Lib.Ajax.Hijack and Lib.Ajax.Call.
0
Slick812Commented:
greetings rssdds, The javascript code to have in  myscript.js  looks like it will work, however, the code author used some rather "Tangled Up" code writes to do this thing for an Ajax Request. The whole thing is wrapped in an unnecessary Lib Object, they have made the way you Use the Ajax to be "Too Simple" for the form-submit, and yet they have unnecessary code work for this ,

this code in the use of ajax -
function(r) { output.innerHTML = r; }
  is the function that is called by another function, that is called by the actual ajax  "callback" of   xhr.onreadystatechange , and is what will load the Entire Returned Ajax String into the HTML section of the "output".

what the
     function Hijack(form, callback)

does is just to get all input-values from a <form> and place them into a JS Object, then it does the -
     function Call(url, args, type, callback)

and in this method It has to "UnWind" or separate OUT the JS Object properties values, into the URL string, but WHY waist all of that effort? This should have just built the URL string in the Hijack( ) method and passed it to the Call( ) method, no OBJECT is needed!

Also this uses the JS escape( ) to do the URL, and THAT is INEFFECTIVE, a No Go!
I use  encodeURIComponent( ) or I have problems.

What is your reason for this question, An explanation of the functioning for code, or your use in a web site?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Robert SilverSr. Software EngineerAuthor Commented:
Could you show me what you mean with a simple rewrite? Its strictly academic.
 here. If not perhaps you guys could answer the question
What am I returning here ? An object with two fields?
again it looks very JSON so I ask again what am I returning very simply as Javascript is not so well typed,
as the method return value being an anonymous function is basically undefined what is the output of this exactly that I am returning an Object containing two fields????
what would it literally look like?? It is not a string right?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Slick812Commented:
OK, not sure how to talk about what you ask, because you do not say things that indicate you understand javascript code?
you ask -

1. What am I returning here ? ? ? Returning from what?  If you mean returning from the ajax request, it's this string -  xhr.responseText  -  Just for your Information, there is NO WAY to know whats in that string called "responseText" because it's received from the SERVER, and can be any string with any content.

2. An object with two fields? ? ? If on the other hand, by "returning here", you mean the
return { Hijack: Hijack, Call: Call };
then yes it is a JSON with 2 properties(elements) Hijack and Call , however the code writer used a very confusing way to write this as the same exact NAMES for the property and the variable , so who can tell what is what? ? not you it seems?

3. value being an anonymous function? ? ? Not so sure I follow this? the Lib.Ajax as method Ajax is defined, also the  Lib.Ajax.Hijack( ) as method Hijack is also defined, however, it looks like to me that this code writer just learned that you can wrap the Ajax method in the Lib object and use a single line call as Lib.Ajax.Hijack( ) to initialize the Ajax XMLHttpRequest AND do the Hijack method in one line, I would never do it like this, but it does have a single line o code to get it going.

4. exactly that I am returning an Object containing two fields? what would it literally look like?? It is not a string right? ? ? , YES "it is not a string"! ! but I can not answer -"what would it literally look like" except to say that it is the methods in the code you have in that  myscript.js file thing.
= = = = = = = = = = = = =

You need to find out more about understanding javascript code, and if interested in Ajax XMLHttpRequest, you need to research and learn about that

I did this following code for this question, and I tested it for getting a HTML form elements and "POST" those by AJAX to a PHP server, first the html page for the FORM and the javascript for ajax-
<!DOCTYPE html>
<html><head><title>Form Ajax test</title><style>body{background:#fff9e8;height:100%;} .names{border:1px solid #da8;}</style></head>
<body><h3>Form Ajax test</h3>

<form name="aform" id="afm" action="formt.php" method="get" onsubmit="doForm(this); return false;" style="width:690px;background:#fec;">
You must have ALL fields below completed or not, LOL<br />
<select name="cars[]" id="c1" multiple="multiple">
  <option value="volvo" selected>Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
  <option value="ford">Ford</option>
  <option value="buick">Buick</option>
</select>
<div class="names">
<fieldset>
    <legend>Personal:</legend>
Full Name: <input type="text" name="full" size="38" maxlength="40" value="" /><br />
User Name: <input type="text" name="user" size="28" maxlength="28" value="" /><br />
</fieldset>
</div>
Email: <input type="text" name="email" size="36" maxlength="48" value="" /><br /><input type="checkbox" name="ck1" value="yes"/> <input type="checkbox" name="ck2" value="not:now"/>
<input type="radio" name="rdo" value="Flip" checked /> <input type="radio" name="rdo" value="HOT"/> <input type="radio" name="rdo" value="KooL"/><br />
Comment: <textarea name="com" cols="55" rows="6" wrap="physical">OK</textarea>
<input type="submit" name="update" value="Update" onclick="subm = this;"> <input type="submit" name="delete" value="TakeOut" onclick="subm = this;">
</form>
Ajax responce=
<pre id="pr1">NON</pre>
<script>/* <![CDATA[ */
function id2dom(elmt1){return document.getElementById(elmt1);}
if(document.all){id2dom=function(elmt1){return document.all[elmt1];}}
function setEl(elmt1,out1){var ob=id2dom(elmt1);ob.innerHTML=out1;ob=null;}

function doForm(fm){
var url= '', els = fm.elements;
var k=0, fs=false;	
for (var i = 0; i < els.length; i++) {
if(els[i].type=="fieldset" && els[i].disabled){fs = els[i]; continue;}
  if (els[i].name) { if(els[i].disabled || els[i].parentNode == fs) continue;
    if(els[i].type=="checkbox" || els[i].type=="radio") if(!els[i].checked) continue;
    if(els[i].type=="select-multiple" && (els[i].name.indexOf("[]")>-1)) {
      for(var o = 0; o < els[i].options.length; o++){
      if(els[i].options[o].selected){if(k>0)url+='&';k++;
      url+= encodeURIComponent(els[i].name)+"="+encodeURIComponent(els[i].options[o].value);}
      }
    continue;}
    if(els[i].type=="submit") if(els[i]!=subm) continue;
    if(k>0)url+='&';k++;
    url+= encodeURIComponent(els[i].name)+"="+encodeURIComponent(els[i].value);
//s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );val.replace( /\r?\n/g, "\r\n" )
    }
  }
//return s.join( "&" ).replace( "%20", "+" ); 9549
//return url.replace(/%20/g, "+" );
ajaxO.doAjax(url.replace(/%20/g, "+" ));
}

function ajaxObj(){
this.busy = false;
this.ajax = false;
/*@cc_on
@if (@_jscript_version>=5)try{this.ajax=new ActiveXObject('Msxml2.XMLHTTP.4.0');} catch(e){
	try{this.ajax=new ActiveXObject("Msxml2.XMLHTTP");} catch(e){
	try{this.ajax=new ActiveXObject("Microsoft.XMLHTTP");} catch(E){this.ajax=false;}}}
	@else this.ajax=false;
@end @*/
if(!this.ajax&&typeof XMLHttpRequest !='undefined'){try{this.ajax=new XMLHttpRequest();} 
catch(e){this.ajax=false;}}

if(!this.ajax){this.busy = true;alert('ERROR - Your Web Browser does NOT have the functions to have Ajax work!');return;}

this.doAjax = function(snd){
  if (this.busy) return;
  this.ajax.open("POST","ajform.php",true);
  if(this.ajax.timeout)this.ajax.timeout=3100;
  var ajo = this;
  this.ajax.onreadystatechange= function (){
    if(ajo.ajax.readyState==4){
    ajo.busy=false;
    if(ajo.ajax.status==200){
    if(ajo.ajax.responseText.length<5){alert("ERROR - Server responce text less than FIVE");return;}
    setEl("pr1",ajo.ajax.responseText);
	} else alert("ERROR - Server Unable to Return. erroe code: "+ajo.ajax.status);
	}
	}
  this.busy=true;
  this.ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  this.ajax.setRequestHeader ("Content-length",snd.length);
  this.ajax.setRequestHeader ("Connection","close");
  this.busy=true;
  this.ajax.send(snd);
  }
}
var ajaxO = new ajaxObj();
/* ]]> */</script>
</body></html>

Open in new window

next is the SERVER code for PHP, which does not do anything but send back the contents of the PHP $_POST to hopefully verify that the FORM Values were ALL sent by Ajax -
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
// Change the Type to text/plain
header('Content-Type: text/plain');

var_dump($_POST);
?>

Open in new window

this works in a couple of browsers and on my server, BUT Please Note! the crappy code in your javascript can not successfully get form elements with -
var f = form.elements[j];
if (f.name) args[f.name] = f.value;

it just plain can NOT WORK, getting form elements is much more complex.
0
Slick812Commented:
after I posted, I saw the original question, and you do not have the experience to dissect the code to understand it, first it declares and empty ob ject
var Lib = Lib || {};

next it adds a method -
Lib.Ajax = (function() {
but because there is a (  before the  function() the method Ajax is called, and that method Ajax returns
{ Hijack: Hijack, Call: Call }

however I have never ran this code, so I do not know if it works? But I do not understand WHY or like the code arrangements, , ,  you can chain methods in JS, so this seems kinda not useful and confusing to me. hope this helps you to grasp something, but my view is to abandon this code work as bad code example and move on to better teaching examples.
0
Robert SilverSr. Software EngineerAuthor Commented:
So as I understand it I am returning an object of two javascript methods with variables Hijack and Call respectively
and their values the methods with the same names all so they can both  be called from the caller
0
Robert SilverSr. Software EngineerAuthor Commented:
For the record I have been using Javascript since it was first written. A lot has changed since 1995 when we were using
Document.write statements.  I am unfamiliar  JSON literals within the Javascript code but I  now understand thanks to answer  that the statement return {Hijack: "Hijack", Call: "Call" }
is in fact a literal Object of two methods
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.