Go Premium for a chance to win a PS4. Enter to Win


I just need to understand what the following actually does

Posted on 2014-04-23
Medium Priority
Last Modified: 2014-05-17
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
Question by:Robert Silver
  • 3
  • 3
LVL 35

Expert Comment

ID: 40018838
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.
LVL 34

Accepted Solution

Slick812 earned 2000 total points
ID: 40020611
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?

Author Comment

by:Robert Silver
ID: 40040598
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?
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

LVL 34

Expert Comment

ID: 40040808
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>
<div class="names">
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 />
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;">
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++){
      url+= encodeURIComponent(els[i].name)+"="+encodeURIComponent(els[i].options[o].value);}
    if(els[i].type=="submit") if(els[i]!=subm) continue;
    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;
@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();} 

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;
  var ajo = this;
  this.ajax.onreadystatechange= function (){
    if(ajo.ajax.responseText.length<5){alert("ERROR - Server responce text less than FIVE");return;}
	} else alert("ERROR - Server Unable to Return. erroe code: "+ajo.ajax.status);
  this.ajax.setRequestHeader ("Content-length",snd.length);
  this.ajax.setRequestHeader ("Connection","close");
var ajaxO = new ajaxObj();
/* ]]> */</script>

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 -
ini_set('display_errors', 1);
// Change the Type to text/plain
header('Content-Type: text/plain');


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.
LVL 34

Expert Comment

ID: 40040858
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.

Author Closing Comment

by:Robert Silver
ID: 40072205
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

Author Comment

by:Robert Silver
ID: 40072220
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses

916 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question