Solved

I just need to understand what the following actually does

Posted on 2014-04-23
7
259 Views
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
0
Comment
Question by:Robert Silver
  • 3
  • 3
7 Comments
 
LVL 34

Expert Comment

by:gr8gonzo
Comment Utility
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
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
Comment Utility
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
 
LVL 2

Author Comment

by:Robert Silver
Comment Utility
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
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 33

Expert Comment

by:Slick812
Comment Utility
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
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
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
 
LVL 2

Author Closing Comment

by:Robert Silver
Comment Utility
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
 
LVL 2

Author Comment

by:Robert Silver
Comment Utility
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

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
OverviewThis article demonstrates a simple search form using AJAX. The purpose of the article is to demonstrate how to use the same code to render a page and javascript (JQuery) and AJAX to make subsequent calls to refine the results. The princip…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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)

772 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now